text:
Q: typ3 content element header render as h1 I'm using typo3 7.6.3 and have a problem with the content element header.
It's rendered as

Tag, but I want to render it as

Tag
Whats the correct TypoScript to do that?
Thanks!
Constants
content.defaultHeaderType = 1

setup
page = PAGE
page {
  config.simulateStaticDocuments = 0
   config.baseURL = http://www.domain.de/
   config.tx_realurl_enable = 1

  config.doctype = html5
  meta.author = domain.de
  meta.publisher = domain.de
  meta.keywords = eins zwei
  meta.description = domain.de text
  meta.revisit-after = 7 days
  meta.robots = all
  meta.rating = general
  meta.viewport = width=device-width, initial-scale=1, maximum-scale=1
  meta.PAGE-TOPIC = Information
  meta.PAGE-TYPE  = Information

  shortcutIcon = fileadmin/design/images/favicon.png

  includeCSS {
    screen1 = fileadmin/design/css/bootstrap.css
    screen1.title = display
    screen1.media = screen

  screen2 = fileadmin/design/css/style.css
  screen2.title = display
  screen2.media = screen

  screen3 = fileadmin/design/css/font-awesome.min.css
 screen3.title = display
  screen3.media = screen

}

includeJS {
file1 = fileadmin/design/js/jquery-2.2.0.min.js
file2 = fileadmin/design/js/bootstrap.min.js
}

}

page.20 = TEMPLATE
page.20.template = FILE
page.20.template.file = fileadmin/design/index.html
page.20.marks{
CONTENTLEFT < styles.content.getLeft
CONTENTLEFT.renderObj.stdWrap.dataWrap=
|

CONTENTRIGHT< styles.content.getRight
CONTENTRIGHT.renderObj.stdWrap.dataWrap=
|

CONTENT < styles.content.get
CONTENT.renderObj.stdWrap.dataWrap=
|

MENU = HMENU
MENU.entryLevel = 0
#NAVIMAIN.excludeUidList =

MENU {
1 = TMENU
1 {
expAll = 1

NO.allWrap =
|

NO.ATagTitle.field = abstract // description // title

ACT = 1
ACT.wrapItemAndSub =
|

ACT.ATagTitle.field = abstract // description // title

IFSUB = 1
IFSUB.before =
IFSUB.after =
IFSUB.doNotLinkIt = 1
IFSUB.wrapItemAndSub =
|

IFSUB.ATagTitle.field = abstract // description // title

ACTIFSUB = 1
ACTIFSUB.before =
ACTIFSUB.after =
ACTIFSUB.doNotLinkIt = 1
ACTIFSUB.wrapItemAndSub =
|

ACTIFSUB.ATagTitle.field = abstract // description // title

wrap =
|

}

   2 = TMENU
 2 {
expAll = 1

ACT = 1
ACT.wrapItemAndSub =
|

ACT.ATagTitle.field = abstract // description // title

ACTIFSUB = 1
ACTIFSUB.wrapItemAndSub = |
ACTIFSUB.before =

ACTIFSUB.after =

ACTIFSUB.doNotLinkIt = 1
ACTIFSUB.ATagTitle.field = abstract // description // title

NO.allWrap =
|

NO.ATagTitle.field = abstract // description // title

IFSUB = 1
IFSUB.before =

IFSUB.after =

IFSUB.doNotLinkIt = 1
IFSUB.ATagTitle.field = abstract // description // title

SPC = 1
SPC.allWrap =

|

wrap =
|

}

}
}

UPDATE 2
in css_styled_content/static i found this:

UPDATE 3

A: In your TypoScript template in the Constants field you have the line like:
content.defaultHeaderType = 2

which determines the default header as H2, definitely that was set by somebody, as default value is H1.
If that's not the clue that means that somebody interfered the CSS Styled Content even more, you just need to preview TypoScript template(s) and search for the place where it's done.


text:
Q: Java collision detection between two Shape objects? I would like to know the best way to tell if a Shape object intersects another shape.
Currently I have collision detection in my game sorted out as long as it involves a Shape intersecting a Rectangle or vice versa. The problem I'm having is that the intersects() method in the Shape class can only take a Rectangle or a Point as a parameter, not another Shape. Is there an efficient way to test if two Shape objects are overlapping in any way?
One way I tried was using a for loop to generate an area of points to test if they were in the shape, and then building an array of Point objects to send to the other shape to test, but this significantly dropped my framerate because of all of the unnecessary comparisons.
I looked and looked for something similar on here but didn't find anything really. Sorry in advance if this is a repeat.

A: Not tested, but why not:
import java.awt.geom.Area;

...

public static boolean testIntersection(Shape shapeA, Shape shapeB) {
   Area areaA = new Area(shapeA);
   areaA.intersect(new Area(shapeB));
   return !areaA.isEmpty();
}

Area implements Shape, but adds some potentially useful methods

A: You can also use the bounds of the shape itself and then compare the bounds:
public boolean collidesWith(Shape other) {
    return shape.getBounds2D().intersects(other.getBounds2D());
}

This is a bit nicer on the eyes.

A: Even though user2221343 already answered Monkeybro10's question, I thought it might be helpful in some cases to know, that the outline of a shape might play a role if you use his described technique:
For example, if you draw two polygons, the collision of them won't be detected if it occurs only on the exact outline of the polygons. Only, if the areas that are included inside the polygons' outlines will overlap, the collision is detected.
If you fill two polygons, but don't draw them, the collision will be detected even on the outline of the visible area.
I wrote a small example to show what I mean. Either uncomment the draw or fill command, and rise the second polygon vertically by one pixel by uncommenting the given line. Run the code and watch the result in the JFrame. If the second Polygon is risen, and both polygons are only visible by the "fill" command, they intersect with their outlines and collision is detected. If the second polygon is not risen, and both polygons are visible by the "draw" command, they intersect with their outlines but collision is not detected:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.geom.Area;

import javax.swing.JFrame;

public class Test {

    private JFrame frame;
    private Polygon polygon1;
    private Polygon polygon2;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Test window = new Test();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Test() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame(){
            private static final long serialVersionUID = 1L;

            @Override
            public void paint(Graphics g){

                super.paint(g);

                doDrawing(g);

            }
        };
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        int nShape1 = 4;
        int xPoly1[] = {30,50,50,30};
        int yPoly1[] = {30,30,50,50};
        polygon1 = new Polygon(xPoly1,yPoly1,nShape1);

        int nShape2 = 4;
        int xPoly2[] = {35,55,55,35};
        int yPoly2[] = {50,50,70,70};

        // uncomment next line to rise second polygon vertically by one pixel
        //yPoly2[] = {49,49,69,69};

        polygon2 = new Polygon(xPoly2,yPoly2,nShape2);
    }
    public synchronized void doDrawing(Graphics g){
        g.setColor(new Color(255,0,0));

        // if you draw the polygon, collision on the exact outline won't be detected.
        // uncomment draw or fill command to see what I mean.
        g.drawPolygon(polygon1);
        g.fillPolygon(polygon1);

        g.setColor(new Color(0,0,255));

        // if you draw the polygon, collision on the exact outline won't be detected.
        // uncomment draw or fill command to see what I mean.
        g.drawPolygon(polygon2);
        g.fillPolygon(polygon2);

        Area area = new Area(polygon1);
        area.intersect(new Area(polygon2));
        if(!area.isEmpty()){
            System.out.println("intersects: yes");
        }
        else{
            System.out.println("intersects: no");
        }
    }

}

A: If you think the area intersect is too expensive, you could first do a bounds check:
     shapeA.getBounds().intersects(shapeB.getBounds())
If this passes, then do the area intersect check.
if( myShape.getBounds().intersects(otherShape.getBounds()) ){
    Area a = new Area(myShape);
    a.intersect(new Area(otherShape));
    if(!a.isEmpty()){
        // do something
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add nth-child() style in inline styling? How can I add a nth-child(n) declaration while applying inline styles to an element (which, obviously, contains multiple elements).
For example, suppose I have a div that contains three p elements.
The general stylesheet rules would go like this:
div p:nth-child(2) {
  color: blue;
}

But how can I still colour the second paragraph blue while applying an inline style to the containing div?

A: Assuming the reason you want to apply the nth-child(n) declaration as an inline style is because you can't edit the CSS file or don't want to; but rather you need to apply your styling directly on the page, you could try just adding a

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

I should note: this is not the ideal way to structure your code. Styles and HTML/content should be separated to create properly formatted and semantic markup.
Also, if you have to apply this styling in more than one place, it can become messy and/or inconsistent. However, I understand that sometimes you have to make exceptions depending on the project.

A: An inline style attribute only pertains to the element with the attribute. So for example, if you have a style attribute on a div, the styles will only apply to that div (inherited properties and conflicting styles notwithstanding). You cannot target a different element using an inline style attribute on another element.
Even if you apply a style attribute onto a p element, you can't make the inline styles apply conditionally based on a pseudo-class. See my answer to this question for why. However, if the markup is dynamically generated, you can control whether or not the style attribute gets printed in the first place using similar logic, but that is outside the scope of your question.

A: li:nth-child(10n-2) {
    background: red;
}

This is the base for my source code!


text:
Q: Turining An HTML  into a link ASP.NET MVC I'd like to be able to turn rows of an html table into links to controllers.
I figured something like
<td onclick="<%:Html.ActionLink("", "Index", new {id=item.user_id}) %>">

I'm using MVC 2
Thanks.

A: <td onclick="window.location='<%:Url.Action("Index", new {id=item.user_id}) %>'">

The onclick attribute accepts some javascript code to execute. If you simply give it a URL, javascript doesn't know what to do with that.
In the snippet above, you're setting the window.location property to the desired URL. This causes the browser to go there.
EDIT: I also just realized that you were using the Html.ActionLink() method which actually generates an  tag in your code. You'd be better off using the Url.Action() method, which actually generates a URL.


text:
Q: How Get All Camera Devices ID From PowerShell I am trying to get all camera devices ID and respective names using PowerShell command line. I tried several commands, but nothing has done what I am aiming. Below my "best" approach:
Get-CimInstance Win32_PnPEntity | where caption -match 'camera'

output

Caption                     : Remote Desktop Camera Bus
Description                 : UMBus Enumerator
InstallDate                 :
Name                        : Remote Desktop Camera Bus
Status                      : OK
Availability                :
ConfigManagerErrorCode      : 0
ConfigManagerUserConfig     : False
CreationClassName           : Win32_PnPEntity
DeviceID                    : UMB\UMB\1&841921D&0&RDCAMERA_BUS
ErrorCleared                :
ErrorDescription            :
LastErrorCode               :
PNPDeviceID                 : UMB\UMB\1&841921D&0&RDCAMERA_BUS
PowerManagementCapabilities :
PowerManagementSupported    :
StatusInfo                  :
SystemCreationClassName     : Win32_ComputerSystem
SystemName                  : DESKTOP
ClassGuid                   : {4d36e97d-e325-11ce-bfc1-08002be10318}
CompatibleID                :
HardwareID                  : {UMB\UMBUS}
Manufacturer                : Microsoft
PNPClass                    : System
Present                     : True
Service                     : umbus
PSComputerName              :

I know, for example, that generally the integrated camera has a name "integrated camera" with a ID "0". But this is not what is being shown.

A: Get-CimInstance Win32_PnPEntity | ? { $_.service -eq "usbvideo" } | Select-Object -Property PNPDeviceID, Name


text:
Q: How to Control Android back stack Lets say I have
A->B->C->D->E
In android back stack.  I want to be able to get back to one of the following:
A->B->C
A->B
A

How can I achieve this?  Hopefully without forcing back button clicks.

A: Use FLAG_ACTIVITY_CLEAR_TOP flag.
Intent a = new Intent(this, A.class);
a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(a);

A: Actually , to go "up" to the activity of your choice, you should use the "up" navigation as used on the action bar:
/** used to handle the "up" button on the action bar, to go to the defined top activity as written on the manifest */
public static void goUpToTopActivity(final Activity currentActivity) {
    final Intent intent = NavUtils.getParentActivityIntent(currentActivity);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    NavUtils.navigateUpTo(currentActivity, intent);
}

in order to use it, you must set on the manifest to which activity this function should use (or you could of course set it yourself by changing the code) :
if you use actionBarSherlock, for each activity that you wish to let to go up, use:
<meta-data
    android:name="android.support.PARENT_ACTIVITY"
    android:value="com.your_app.activities.MainActivity" />

if you use the android framework (if your minSdk version is API 16 and above), use the "parentActivityName" attribute.

A: Using the image and information from the official developers page on Android tasks and back stack you can see that of all other ways to launch an Activity you can ensure such behavior only using the FLAG_ACTIVITY_CLEAR_TOP in your Intent flags.
Your regular back button proceeds as:

But when you specify this flag, you get a behavior like you need, as given by an example at this source:

consider a task consisting of the activities: A, B, C, D. If D calls
  startActivity() with an Intent that resolves to the component of
  activity B, then C and D will be finished and B receive the given
  Intent, resulting in the stack now being: A, B.

A: Suppose you are using Intent to move to another activity
Intent i = new Intent(A.this,B.class);
startActivity(i);

this code will take you to the 'B' Activity and when you press Back button it will again take you to the 'A' Activity . If you dont want to go back to activity 'A' you can use....
Intent i = new Intent(A.this,B.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);

For more information about Back Stack in Android Follow this link :
http://developer.android.com/guide/components/tasks-and-back-stack.html


text:
Q: Default @Autowired not injecting This is a simple Spring bean, where one of the fields complexMsg is autowired. But on running, the bean is null. Spring version is 3.2.
Similar issue has been posted earlier, the solution of which is already existing in my code.
Bean code :
public class GreetingServiceImpl implements IGreetingService {
private String simpleMsg = null;
//Autowired annotation is equivalent to autowire="byType"
@Autowired
private ComplexMessage complexMsg ;

public String getSimpleMsg() {
    return simpleMsg;
}
     ...

Spring config xml :
   <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:annotation-config />
<bean id="greetingBean" class="simple.GreetingServiceImpl">
    <property name="simpleMsg" value="HelloWorld!!" />
</bean>
<bean id="complexMsg" class="simple.ComplexMessage">
    <property name="receiver" value="Raka" />
    <property name="content" value="MerryChristmas" />
</bean>
</beans>

Main class :
public static void main(String[] args) {
    IGreetingService greetingSrvc = null;
    BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource("greetingConfig.xml"));
    greetingSrvc =(IGreetingService) beanFactory.getBean("greetingBean");

greetingSrvc.complexMsg is null.

A: probably you missed out on the component scan?

<context:component-scan base-package="simple"/>

it this .class file is in a .jar file probably you could add the

@Component

annotation in addition to the

@Service

annotation.
eg:

@Service @Component public class Abc{}

A: I have tried it and it is working for me, i used application context here.
your beans.xml file content was not appropriate i changed it..
let me know for anything else..
see below for my full code
beans.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<bean id="greetingBean" class="com.kb.autowiring2.GreetingServiceImpl">

</bean>
<bean id="complexMsg" class="com.kb.autowiring2.ComplexMessage">

</bean>
</beans>

package com.kb.autowiring2;

public interface IGreetingService {
    public ComplexMessage getComplexMsg();

}

package com.kb.autowiring2;

import org.springframework.beans.factory.annotation.Autowired;

public class GreetingServiceImpl implements IGreetingService {
    @Autowired
    private ComplexMessage complexMsg ;

    public ComplexMessage getComplexMsg() {
        return complexMsg;
    }

}

package com.kb.autowiring2;

public class ComplexMessage {

}

package com.kb.autowiring2;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.kb.autowiring1.Person;

public class Client {

    public static void main(String[] args) {
         IGreetingService greetingSrvc = null;
         ApplicationContext applicationContext = new ClassPathXmlApplicationContext("com/kb/autowiring2/beans.xml");
            IGreetingService p = applicationContext.getBean("greetingBean",IGreetingService.class);
            System.out.println(p.getComplexMsg());

    }

}

A: I really think you should use ApplicationContext other tan BeanFacotry. The reason is that ApplicationContext implements 1 interface which I think is BeanPostProcessor And BeanFacotry doesn't. Note beanfactory is short of features, such as @Transational.


text:
Q: Modified volume size on the EBS volume doesn't reflect it's new size, it still shows up original size I have currently modified AWS EBS volume (volume type is gp2). The original size of disk is 50G,I have increased to 100G. The system is CentOS 7
That disk has MySQL server installed and has ibdata files and the EBS volume does not have any partitions.
After modifying the disk size, lsblk shows the correct size:
xvdf    202:80   0  100G  0 disk /var

But df -h still shows originial size:
/dev/xvdf        50G  9.9G   37G  22% /var

Is there anything else I should run? I tried to reboot the EC2 instance but still no luck.

A: You should be able to run sudo resize2fs -p /dev/xvdf to grow the filesystem to fit the expanded size of the volume.  As with any such operation, it should be quite safe, but don't try it without a backup.
(-p is for a progress bar)


text:
Q: on click append and replace portion of div to another div I have a fiddle set up , i'm just learning and getting a bit confused on how to make this work.
https://jsfiddle.net/twxxwj1m/6/
When i click on any text "select" it opens a hidden container with names that i want to be able to add to the container i just clicked "select" from. So if i click on the "select" text in the box container labled QB - Select Quarterback , and a new box opens that lists a few players to add , i want to click "add" on any of those boxes , I want to remove that div from the available list and add it to the starting list in place of where i originally made the select from. I'm confused and probably even more confusing trying to describe this.
$("#available-players .quarterbacks").hide();
$("#available-players .runningbacks").hide();
$("#available-players .widereceivers").hide();
$("#available-players .tightends").hide();
$("#available-players .flex").hide();
$("#available-players .defense").hide();
$("#available-players h1").hide();

$(".quarterbacks .show-players").click(function(){
    $("#starting-players").hide();
    $("#available-players .quarterbacks,#available-players h1").show();
});
$(".runningbacks .show-players").click(function(){
    $("#starting-players").hide();
    $("#available-players .runningbacks,#available-players h1").show();
});
$(".widereceivers .show-players").click(function(){
    $("#starting-players").hide();
    $("#available-players .widereceivers,#available-players h1").show();
});
$(".tightends .show-players").click(function(){
    $("#starting-players").hide();
    $("#available-players .tightends,#available-players h1").show();
});
$(".flex .show-players").click(function(){
    $("#starting-players").hide();
    $("#available-players .flex,#available-players h1").show();
});
$(".defense .show-players").click(function(){
    $("#starting-players").hide();
    $("#available-players .defense,#available-players h1").show();
});

$(".quarterbacks .add-players").click(function(){
    $("#available-players .quarterbacks,#available-players h1").hide();
    $("#starting-players").show();
});
$(".runningbacks .add-players").click(function(){
    $("#available-players .runningbacks,#available-players h1").hide();
    $("#starting-players").show();
});
$(".widereceivers .add-players").click(function(){
    $("#available-players .widereceivers,#available-players h1").hide();
    $("#starting-players").show();
});
$(".tightends .add-players").click(function(){
    $("#available-players .tightends,#available-players h1").hide();
    $("#starting-players").show();
});
$(".flex .add-players").click(function(){
    $("#available-players .flex,#available-players h1").hide();
    $("#starting-players").show();
});
$(".defense .add-players").click(function(){
    $("#available-players .defense,#available-players h1").hide();
    $("#starting-players").show();
});

Is what i have so far the easiest and best method to do this ?


text:
Q: Prevent >1 person from running VBA macro at a time (shared wkb) What I'm aiming at is getting a list of all currently running scripts in order to check if other users aren't running the same VBA macro at the same time (and if yes, then stop the code etc., similar to what the OP of the below question wanted). This would be for a shared workbook (I learned it's not designed for this type of work, but I need to try it).
https://stackoverflow.com/a/36116091/5947935
I've been trying to make the code in the above answer work in VBA, but it seems it's a vbs thing and I would like to avoid that.
I'm not an expert to say the least, so I'm having trouble understanding how to get this to work in Excel VBA. I don't even know if it's possible at all.
I've found this as well: VBA Getting program names and task ID of running processes and it works fine but it only lists the running processes.
I've no idea however how to merge the two... or even if the WMI is the correct way to go.
I'd appreciate any sort of help.

A: I used to create a "locking file" which was just an empty text file with the name of the workbook followed by the username and an extension of .LCK
First thing my code did on auto open was look for a locking file then report back to the user which user had it open then cancel the open.
If it didn't find a locking file then it created one and proceeded as normal. If it found one but it was the same username (ie that user had it crash on them) it proceeded with the open.
The last thing the code did was delete the file.

A: No codes here and theory not tested yet, but the idea of preventing a different user executing a Macro on a shared workbook requires some thinking.
I would create a hidden worksheet, and use one of the cells to store the Environ("USERNAME") when the macro is first started - to indicate who has it running, then clear it when complete, first-in-first-out.

*

*Lets say named range MUser (macro user) is range A1 in that hidden worksheet

*When the macro runs, it will first check if MUser is empty, if so then change it's value to Environ("USERNAME") and Save the file before next step (here I am not certain the value is updated on others session).

*If MUser is not empty, either abort or retry in a few second.

*When macro completes, MUser will be ClearContents, and save the File to free up the workbook for macro.

Idea is here but please test. Post your own code for us to troubleshoot. You may also use Workbook events to "lock" the macro execution this way. Or even use this hidden sheet to make a log record for debug. Also some fail-safe needs to be implemented (such as a time stamp at macro start and override the lock after some minutes).


text:
Q: Trying to mock an API class with RSpec I'm trying to learn how to use RSpec to test that my create_price_type_cache method on the Setting class is being called by the API class instance. I've tried a number of approaches I've googled, but I figure out how to do this, or even if I should write my API class differently.
The test below gives me the error:
undefined method `api_endpoint' for #<Rails::Application::Configuration:0x00000107376420>

# setting_spec.rb
it "should call get_price_type_list from the API" do
  price_types = [build(:price_type)]

  api = mock_model(Api.instance)
  api.stub!(:get_price_type_list).and_return(price_types)
  expect(Api.instance.should_recieve(:get_price_type_list).and_return(api)).to eq [price_types]
end

# setting.rb
class Setting
  def self.create_price_type_cache
    array = Api.instance.get_price_type_list
    ActiveRecord::Base.transaction do
      CachePriceType.delete_all
      array.each do |e|
        e.save!
      end
    end
  end
end

# api.rb
class Api
  def self.instance
    @instance ||= new
  end

  def get_price_type_list
    # Makes an API call and returns an array of objects
  end
end

Thanks.
Edit:
Thank you jstim for waking me up, I confused myself after looking at this for so long. I've stubbed out the config settings for my Api class and this seems to be working, but is that the best way to do it, or should I mock the Api class like I originally tried?
This is my current passing test:
Rails.application.config.stub(:api_endpoint).and_return("")
price_types = [build(:cache_price_type)]
Api.instance.stub(:get_price_type_list).and_return([price_types])
Array.any_instance.stub(:save!)
expect {Setting.create_price_type_cache}.to_not raise_error

A: I'm still not sure if this is the best approach, since I'll have to stub every config setting in my Api class, but this is what I ended up using as my final test for now:
Rails.application.config.stub(:api_endpoint).and_return("")
price_types = [build(:cache_price_type)]
Api.instance.stub(:get_price_type_list).and_return([price_types])
Array.any_instance.stub(:save!)
expect {Setting.create_price_type_cache}.to_not raise_error


text:
Q: Cannot drop database with logical replication I cannot drop database having logical replication SUBSCRIPTION, when i try to dropdb i get an error saying that the database contains a subscription but when i try to drop the SUBSCRIPTION i get an error saying the replication slot does not exist.

A: Check out the fine documentation:

If this fails, either because the remote host is not reachable or because the remote replication slot cannot be dropped or does not exist or never existed, the DROP SUBSCRIPTION command will fail. To proceed in this situation, disassociate the subscription from the replication slot by executing ALTER SUBSCRIPTION ... SET (slot_name = NONE).


text:
Q: Change SVG fill of only the element being hovered over For some reason I can not get my hover to work properly.  It changes the fill of every item that has the same class and I am not sure why.  I am using DEFS and USE which is different from all the examples I have seen that work the way I want.
The included code has been simplified to two rectangles and I only want the one hovered over to change color.
CSS
rect
{
    stroke-width : 3;
    stroke : black;
    width : 300;
    height : 100;
    rx : 15;
    ry : 15;
}

text
{
    stroke : black;
    fill : gold;
    text-anchor : middle;
    pointer-events: none;
}

.client
{
    fill : lightsalmon;
}

.client:hover
{
    fill : green;
}

HTML
<!DOCTYPE HTML>
<HTML>
    <HEAD>
        <LINK rel="stylesheet" type="text/css" href="Test.css">
    </HEAD>
    <BODY>
        <DIV id="svgDiv">
            <SVG id="svgDoc" width="100%" viewBox="0, 0, 1500, 1000">
                <DEFS>
                    <G id="table">
                        <RECT width="300" height="90" />
                    </G>
                </DEFS>

                <G id="clientTables" transform="translate(0, 250) scale(0.5 0.5)" class="client">
                    <G id="TCLNT" transform="translate(500, 250)">
                        <USE xlink:href="#table" />
                        <TEXT x="150" y="50">TEST_CLNT</TEXT>
                    </G>
                    <G id="TCPHN" transform="translate(50, 50)">
                        <USE xlink:href="#table" />
                        <TEXT x="150" y="50">TEST_CLNT_PHN</TEXT>
                    </G>
                </G>
            </SVG>
        </DIV>
    </BODY>
</HTML>

A: The .client class is a wrapper for two elements. For this reason, you get targeting both elements when hovering.
It is necessary to connect the <g> tag to the :hover selector. Do it like this:
.client g:hover {
  fill : green;
}


text:
Q: can't login into my codeigniter app after long time of usage it's been a while since i've purchased freelancer office on codecanyon. i'm using it since 2015. I've never had an issue till last week. If I type in a wrong password it gives me an error (which is normal :D) however when i type the correct one it just reloads the page :/ i've set the ENVIRONMENT to production but no error messages.. except for deprecated each() call in mx/modules.php file.
Codeigniter version: v3.1.0
php version : 7.1
app url:
http://app.wolftech.eu
i've the same error with another 'app' that ive bought on codecanyon for a friend of mine. after 1 year of succesfull usage it just reloads the page when attempting to login.

A: Based on the error output that you've provided, I assume that the error comes from codeigniter modular extension hmvc, that show up because it uses each() function that is deprecated.
If you look at one of the official repository pull request, and from this codeigniter forum thread, you could change the third_party/MX/Modules.php files line 83 :
(is_array($module)) ? list($module, $params) = each($module) : $params = NULL;

and replace it to :
if(!is_array($module))
{
    $params = NULL;
}
else
{
    $keys = array_keys($module);
    $params = $module[$keys[0]];
    $module = $keys[0];
}


text:
Q: How to extract data from multiple URL using python Hi i want to scrap data from multiple URL, I am doing like
for i in range(493):
    my_url = 'http://tis.nhai.gov.in/TollInformation?TollPlazaID={}'.format(i)

but it not giving me complete data, it is printing only last url data,
here is my code, plz help
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
import psycopg2
import operator

for i in range(493):
    my_url = 'http://tis.nhai.gov.in/TollInformation?TollPlazaID={}'.format(i)

    uClient = uReq(my_url)
    page1_html = uClient.read()
    uClient.close()
    # html parsing
    page1_soup = soup(page1_html, 'html.parser')

    # grabing data
    containers = page1_soup.findAll('div', {'class': 'PA15'})

    # Make the connection to PostgreSQL
    conn = psycopg2.connect(database='--',user='--', password='--', port=--)
    cursor = conn.cursor()
    for container in containers:
        toll_name1 = container.p.b.text
        toll_name = toll_name1.split(" ")[1]

        search1 = container.findAll('b')
        highway_number = search1[1].text.split(" ")[0]

        text = search1[1].get_text()
        onset = text.index('in')
        offset = text.index('Stretch')
        state = str(text[onset +2:offset]).strip(' ')

        location = list(container.p.descendants)[10]
        mystr = my_url[my_url.find('?'):]
        TID = mystr.strip('?TollPlazaID=')

        query = "INSERT INTO tollmaster (TID, toll_name, location, highway_number, state) VALUES (%s, %s, %s, %s, %s);"
        data = (TID, toll_name, location, highway_number, state)

        cursor.execute(query, data)

# Commit the transaction
conn.commit()

but it's displaying only second-last url data

A: Seems like some of the pages are missing your key information, you can use error-catching for it, like this:
try:
    tbody = soup('table', {"class": "tollinfotbl"})[0].find_all('tr')[1:]
except IndexError:
    continue  # Skip this page if no items were scrapped

You may want to add some logging/print information to keep track of nonexisting tables.
EDIT:
It's showing information from only last page, as you are commiting your transaction outside the for loop, overwriting your conn for every i. Just put conn.commit() inside for loop, at the far end.


text:
Q: CSS3 translateX not working I am trying to animate several items on screen when a menu item is clicked...all animations but one are working as desired. I want to move in the main content (section) of the page from right to left but instead of sliding in it just appears without any transition. This is the relevant css code:
section{
  width: 920px;
  background: rgb(247, 239, 239);
  position: absolute;
  left: 2000px;
  top: 240px;
  padding:20px;
}
.fadeInRight{
  -webkit-transition: 1s ease-in-out;
  -moz-transition: 1s ease-in-out;
  -ms-transition: 1s ease-in-out;
  -o-transition: 1s ease-in-out;
  transition: 1s ease-in-out;
  -webkit-transform: translateX(-2000px);
  -moz-transform: translateX(-2000px);
  -ms-transform: translateX(-2000px);
  -o-transform: translateX(-2000px);
  transform: translateX(-2000px);
}

html code:
<section id="content" class="fadeInRight">

</section>

you can see the code in action here once you click on one of the links in the footer.
Any advise is much appreciated.
Thanks

A: Specify a property that has to be animated:
.fadeInRight{
  -webkit-transition: -webkit-transform 1s ease-in-out;
  -moz-transition: -moz-transform 1s ease-in-out;
  -ms-transition: -ms-transform 1s ease-in-out;
  -o-transition: -o-transform 1s ease-in-out;
  transition: transform 1s ease-in-out;
  -webkit-transform: translateX(-2000px);
  -moz-transform: translateX(-2000px);
  -ms-transform: translateX(-2000px);
  -o-transform: translateX(-2000px);
  transform: translateX(-2000px);
}


text:
Q: C# Coded UI - How to open a pdf file from a link in a web page Using Coded UI in Visual Studio 2017, how do I open a pdf file from a link in a web page?
Here is the segment of code I've written:
// Click on "View our documents" link
        BrowserWindow browser2 = BrowserWindow.Launch(url);
        browser2.Maximized = true;
        UITestControl rpQ3FinReport = new UITestControl(browser2);
        rpQ3FinReport.TechnologyName = "Web";
        rpQ3FinReport.SearchProperties.Add("ControlType", "Hyperlink");
        rpQ3FinReport.SearchProperties.Add("InnerText", "2017 Q3 Financial Report");
        Mouse.Click(rpQ3FinReport);

        // Open the pdf report
        UITestControl rpQ3FinReportPDFOpen = new UITestControl(browser2);
        rpQ3FinReportPDFOpen.TechnologyName = "MSAA";
        rpQ3FinReportPDFOpen.SearchProperties.Add("ControlType", "Button");
        rpQ3FinReportPDFOpen.SearchProperties.Add("Name", "Open");

        Mouse.Click(rpQ3FinReportPDFOpen);

        Playback.Wait(3000);

The above code for rpQ3FinReport clicks the link containing the PDF file, but then in the footer of the web page a message appears to either Open or Save or Cancel the pdf file.
I found the object property info for Open and used rpQ3FinReportPDFOpen to open the PDF, but error message states:

Message: Test method HandCodingWebApp1.CUITHandCoding.StartURL threw
exception:
Microsoft.VisualStudio.TestTools.UITest.Extension.FailedToPerformActionOnHiddenControlException:
Cannot perform 'Click' on the hidden control.
Additional Details:  TechnologyName:  'MSAA' Name:  'Open'
ControlType:  'Button'  --->
System.Runtime.InteropServices.COMException: Exception from HRESULT:
0xF004F002

How do I resolve this issue?
I've attached an image of the web page. Please note that I had to erase some of the identifiable segment from the page.
Thank you.

A: Not sure why it doesn't work for you.
It is possible the the Test is trying to click the control too fast.
Try inserting this here:
openButton.WaitForControlExists();
Playback.Wait(150);
Mouse.Click(openButton);

It waits for the control until its enabled and then clicks it.
The 150ms wait period is because the program might be too fast again.
Also, your code works for me fine. (the same code as yours without the url definition in BrowserWindow and without the clicking of the hyperlink):
BrowserWindow browserWindow = new BrowserWindow();

// Open the pdf report
UITestControl openButton = new UITestControl(browserWindow);
openButton.TechnologyName = "MSAA";
openButton.SearchProperties.Add("ControlType", "Button");
openButton.SearchProperties.Add("Name", "Open");
Mouse.Click(openButton);

You could also try this here where I am defining the browserWindow control myself:
UITestControl browserWindow = new UITestControl();
BrowserWindow.TechnologyName = "MSAA";
BrowserWindow.SearchProperties.Add("ControlType", "Window");
BrowserWindow.SearchProperties.Add("ClassName", "IEFrame");

// Open the pdf report
UITestControl openButton = new UITestControl(BrowserWindow);
openButton.TechnologyName = "MSAA";
openButton.SearchProperties.Add("ControlType", "Button");
openButton.SearchProperties.Add("Name", "Open");

Mouse.Click(openButton);


text:
Q: Proof of a graph problem on degree sequence Prove that:
order of natural number $d_1 , d_2 , \ldots , d_n$ as descending is a ordering graph if and only if the order was sorted as descending $d_2-1, d_3 -1 , \ldots ,d_d -1,\ldots ,d_n$ be ordering graph.
$d_d$ in sequence is d  $d_1$.
(arrangement=order).

A: Hint: If you know that $d=d_1\ge d_2 \ge \dots \ge d_n$ are degrees of vertices of some graph, what can you say about degrees of the graph where the vertex of degree $d_1$ is omitted? Can you go in opposite direction, too? (I.e. can you obtain from a graph with degrees $d_1-1,\dots,d_d-1,d_{d+1},\dots,d_n$ a graph with degrees $d_1,d_2,\dots,d_n$?)
(I assume that the interpretation of your question given in this comment is correct and that the question is about Havel-Hakimi theorem.)


text:
Q: How to select range of records in Oracle I am trying to select a range of records using a SQL Query:
SELECT COMPANY_ID as SEQ_NO, NULL URBAN_CODE
FROM (SELECT COMPANY_ID as SEQ_NO, NULL URBAN_CODE, ROWNUM num from COMPANY_TABLE)
WHERE num > 1 and num < 9

The error I keep getting is "URBAN_CODE": invalid identifier
I saw this solution from several SO pages but for some reason I keep getting this error.. can someone help? Thanks!

A: The code you showed can't complain about URBAN_CODE. But it will give you ORA-00904: "COMPANY_ID": invalid identifier, so maybe you've swapped the column names over in your post.
You're aliasing your COMPANY_ID column in your inline view, but then still trying to refer to the original unaliased name in the outer query. You can either use the alias, or define it later:
SELECT COMPANY_ID as SEQ_NO, NULL URBAN_CODE
FROM (SELECT COMPANY_ID, ROWNUM num from COMPANY_TABLE)
WHERE num > 1 and num < 9

or
SELECT SEQ_NO, URBAN_CODE
FROM (SELECT COMPANY_ID as SEQ_NO, NULL URBAN_CODE, ROWNUM num from COMPANY_TABLE)
WHERE num > 1 and num < 9

There's not much point having the URBAN_CODE in the inline view either if it's always null; doesn't really hurt, but you aren't using that generated (null) value in the outer query.
You're also using ROWNUM without doing any ordering, so your results will be indeterminate. You really need another layer of inline view:
SELECT COMPANY_ID as SEQ_NO, NULL as URBAN_CODE
FROM (
  SELECT COMPANY_ID, ROWNUM num
  FROM (
    SELECT COMPANY_ID
    FROM COMPANY_TABLE
    ORDER BY COMPANY_ID -- or whatever order you want to impose
  )
)
WHERE num > 1 and num < 9;

A: If am not wrong you need to use alias name in outer query.
You cannot use company_Id in outer query because you have given a alias name in sub-select you need to use that.
SELECT SEQ_NO, URBAN_CODE
FROM (SELECT COMPANY_ID as SEQ_NO, NULL as URBAN_CODE, ROWNUM num from COMPANY_TABLE)
WHERE num > 1 and num < 9


text:
Q: Is there a way to stage all changed files before a commit? Right now I'm manually selecting each changed file for staging before committing. I'm curious whether there's a SmartGit equivalent to
git commit -a

perhaps a shortcut to select all changed files (other than those being .gitignored).

A: You can select all changed files in the Files pane with standard OS shortcut. On Windows this is Ctrl+A. Then you can stage the selection as usual.
Note though that if you are going to commit only the whole files, you don't even need to stage them. After you selected files of interest, you can press Commit, and then make sure the "Local Changes" option is picked on the top of the dialog. SmartGit will stage and commit selected files for you automatically.

A: When having selected the repository root directory in the Repositories view and having the focus in this view, operations like Stage and Commit will work on all available files, regardless of which files are currently visible in the Files view (e.g. you might have selected to hide untracked files).


text:
Q: Customize SWRevealViewController I used SWRevealViewController to create a slideout menu for my iOS app. Now I would like to customize it. I've been trying to use this tutorial as a reference http://www.ebc.cat/2015/03/07/customize-your-swrevealviewcontroller-slide-out-menu/. Without knowing Obj-C I haven't had much success.
Specifically, I would like to set rearViewRevealDisplacement = 0. Can someone teach me how to customize using Swift?
Current code (last line):
   if self.revealViewController() != nil {
        slideoutBtn.target = self.revealViewController()
        slideoutBtn.action = Selector("rightRevealToggle:")
        self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) //swipe
        self.view.addGestureRecognizer(self.revealViewController().tapGestureRecognizer()) //tap close
        self.revealViewController().rearViewRevealDisplacement = 0
    }

A: You should to customize SWRevealViewController.m file. Inside SWRevealViewController.m add func:

-(void) customizeSlideOutMenu{
    // INITIAL APPEARANCE: Configure the initial position of the menu and content views
    self.frontViewPosition = FrontViewPositionLeft; // FrontViewPositionLeft (only content), FrontViewPositionRight(menu and content), FrontViewPositionRightMost(only menu), see others at library documentation...
    self.rearViewRevealWidth = 150.0f; // how much of the menu is shown (default 260.0)

// TOGGLING OVERDRAW: Configure the overdraw appearance of the content view while dragging it
self.rearViewRevealOverdraw = 0.0f; // how much of an overdraw can occur when dragging further than 'rearViewRevealWidth' (default 60.0)
self.bounceBackOnOverdraw = NO; // If YES the controller will bounce to the Left position when dragging further than 'rearViewRevealWidth' (default YES)

// TOGGLING MENU DISPLACEMENT: how much displacement is applied to the menu when animating or dragging the content
self.rearViewRevealDisplacement = 60.0f; // (default 40.0)

// TOGGLING ANIMATION: Configure the animation while the menu gets hidden
self.toggleAnimationType = SWRevealToggleAnimationTypeSpring; // Animation type (SWRevealToggleAnimationTypeEaseOut or SWRevealToggleAnimationTypeSpring)
self.toggleAnimationDuration = 1.0f; // Duration for the revealToggle animation (default 0.25)
self.springDampingRatio = 1.0f; // damping ratio if SWRevealToggleAnimationTypeSpring (default 1.0)

// SHADOW: Configure the shadow that appears between the menu and content views
self.frontViewShadowRadius = 10.0f; // radius of the front view's shadow (default 2.5)
self.frontViewShadowOffset = CGSizeMake(0.0f, 2.5f); // radius of the front view's shadow offset (default {0.0f,2.5f})
self.frontViewShadowOpacity = 0.8f; // front view's shadow opacity (default 1.0)
self.frontViewShadowColor = [UIColor darkGrayColor]; } // front view's shadow color (default blackColor)

and call this func from viewDidLoad
- (void)viewDidLoad{
    [super viewDidLoad];
    [self customizeSlideOutMenu];
}

Now you can customize your slide-out menu, just change values in customizeSlideOutMenu func


text:
Q: Thread stack backtraces when program running under valgrind is interrupted I have a server program, which doesn't have a very clean/graceful shutdown (not supposed to terminate in general). When tracing memory leaks, I run it under valgrind, but finally have to kill the process by a signal (^C). Generally I try to terminate the process when the ambiance is quiet but still then some threads might have been busy processing jobs and memory held by them cause false alarms. To assist such analysis, is there any way (tool) in valgrind, so that it can print the backtrace of threads when the program exits (by a signal?).

A: I know it's inconvenient, but could you get your program to dump core when it gets this signal, then diagnose the core dump with gdb?

A: Don't sure I quite understand your question, but you can print backtrace of all pthreads by gdb:
thread apply all bt


text:
Q: If I upgrade to OS X 10.7 (Lion), will Intuit Quicken still work? I heard that my Intuit Quicken 2007 which I use for balancing my checkbook and other business accounts won't work on Lion. Is that true?  I am so dependant on it that I have postponed my Mac's OS upgrade to Lion.  What can i do to work around this issue?

A: Unfortunately, no.  Quicken 2007 requires Rosetta which Apple has decided to leave behind in their OS.  MacWorld.com has a great article here with some great alternatives, but right now, you need to either give up Quicken 2007, or wait on Lion until you are ready to do so.
Dual booting is also possible, but it's not a convenient solution to just run banking software.

A: No, Quicken will not run or work at all under Lion, since Quicken was designed as a PowerPC app, which relies on "Rosetta" emulation (built in to OSX, but no longer present in OSX Lion) to work.
For more info, go here.
At the moment, you should wait until Quicken is updated to Work under Lion, or if you can get by with "Quicken Essentials" (which does work under Lion), you could use this instead.

A: fwiw, I moved to iBank, and love it. It handles transfers between accounts much better than Quicken ever did. It's really mac like, and helps me at tax time. There are a number of others as well, and many have great Quicken import capabilities.
I've never looked back, and converted accounts from 1991 to iBank with ease.
Hope this helps.

A: If you need the features of Quicken and want to move to Lion, your best alternative is to install a Windows virtual machine (Parallels, VMware, Virtual Box) and covert to Quicken for Windows.  That's a lot of complexity and at least a couple of hundred dollars to do so you need to be really sure that Quicken is worth it compared to the alternatives.
There's no indication that Rosetta will ever come back nor that Quicken will update Quicken for Mac so waiting for one of those to happen is just wasting time.

A: Quicken did just announce that they plan to update Quicken 2007 to work with Lion. Sounds like there will be no new features, but they plan to ship in the 1st half of 2012.

A: I solved this one temporarily by setting up an old Mac Mini as a monitor-less server with Snow Leopard and Quicken installed. It sits on a shelf out of the way. When I need to use Quicken, I use screen sharing to log in from my main computer. It is somewhat less awkward and a little quicker than rebooting from a separate partition.
It would be nice to have a real update, but there appears to be faint hope of that.


text:
Q: Get roles of a user in certain portal dotnetnuke i have a dotnetnuke with two portals that share users into 2 portals.
i want get roles of user A in portal 1 in a module in portal 2(in another portal)
how can i do that?

A: int portalId = 1;
UserInfo user = UserController.GetUserById(portalid, UserID);

You can get the list of roles for a user in a specific portal using array: user.Roles or you can check if the user is in a specific role using: user.IsInRole(roleName).


text:
Q: Porque VBA retorna erro de #valor Olá tenho o seguinte código vba que é uma função que recebe três parâmetros e calcula as funções bult-in  tendência e rquad e a depender do resultado ela retorna tendência ou a média dos ultimos valores.
Function CAPACIDADEPORT(KY As Range, KX As Range, UX)

    Dim RQUAD As Double
    Dim TENDE As Variant

    RQUAD = Application.WorksheetFunction.RSq(KY.Value, KX.Value)
    TENDE = Application.WorksheetFunction.Trend(KY.Value, KX.Value, UX.Value)

    If RQUAD > 0.6 Then
        CAPACIDADEPORT = TENDE

    Else:
        CAPACIDADEPORT = Application.WorksheetFunction.Average(KY.Cells(KY.Cells.Count).Offset(-4).Resize(5))
    End If

End Function

Essa função acima funciona normalmente. O problema é quando eu adiciono mais um teste no if(TENDE > 0), após eu mudar ela sempre retorna erro de valor sendo que os dados que eu passo como parametro para as duas são os mesmos.
Function CAPACIDADEPORT(KY As Range, KX As Range, UX)

        Dim RQUAD As Double
        Dim TENDE As Variant

        RQUAD = Application.WorksheetFunction.RSq(KY.Value, KX.Value)
        TENDE = Application.WorksheetFunction.Trend(KY.Value, KX.Value, UX.Value)

        If RQUAD > 0.6 AND TENDE > 0 Then
            CAPACIDADEPORT = TENDE

        Else:
            CAPACIDADEPORT = Application.WorksheetFunction.Average(KY.Cells(KY.Cells.Count).Offset(-4).Resize(5))
        End If

    End Function

Gostaria de saber o que pode estar levando a esse erro.
Grato desde já.

A: A documentação da função deixa a desejar ao informar que retorna um Variant quando na verdade ela retorna um Array de Variant. Você pode verificar isso usando o VarType.
Nos meus testes, mesmo quando passava UX com apenas uma célula ele retornava um Array com 2 valores, sendo o segundo valor a tendência propriamente dita (não tenho certeza do que veio no primeiro elemento). Adicionando (1) na frente do cálculo de TENDE corrigiu o comportamento.
Segue o código corrigido:
Function CAPACIDADEPORT(KY As Range, KX As Range, UX As Range)

    Dim RQUAD As Double
    Dim TENDE As Variant

    RQUAD = Application.WorksheetFunction.RSq(KY, KX)
    TENDE = Application.WorksheetFunction.Trend(KY, KX, UX)(1)

    If RQUAD > 0.6 And TENDE > 0 Then
        CAPACIDADEPORT = TENDE

    Else:
        CAPACIDADEPORT = Application.WorksheetFunction.Average(KY.Cells(KY.Cells.Count).Offset(-4).Resize(5))
    End If

End Function


text:
Q: Unable to install numpy in PYCHARM ANACONDA While installing numpy in my Pycharm project interpreter I am getting below error
File "C:\Users\2303p\Anaconda3\lib\site-packages\conda_package_handling\tarball.py", line 7, in <module>
    import libarchive
File "C:\Users\2303p\Anaconda3\lib\site-packages\libarchive\__init__.py", line 1, in <module>
    from .entry import ArchiveEntry
File "C:\Users\2303p\Anaconda3\lib\site-packages\libarchive\entry.py", line 6, in <module>
    from . import ffi
File "C:\Users\2303p\Anaconda3\lib\site-packages\libarchive\ffi.py", line 48, in <module>
    libarchive = ctypes.cdll.LoadLibrary(libarchive_path)
File "C:\Users\2303p\Anaconda3\lib\ctypes\__init__.py", line 434, in LoadLibrary
    return self._dlltype(name)
File "C:\Users\2303p\Anaconda3\lib\ctypes\__init__.py", line 356, in __init__
    self._handle = _dlopen(self._name, mode)
TypeError: LoadLibrary() argument 1 must be str, not None

Can someone help me resolve the same ?

A: In Pycharm, go to File, then Settings, (Ctrl + Alt + S), then click on "Project:python", then "Project Interpreter" make sure you have an active Anaconda interpreter next to the "Project Interpreter:" drop-down menu. From here you should be able to click on the "+" sign next to "Latest Version". This will open a window titled "Available Packages" from here you should be able to search for numpy then click install package.
As an alternative:
Click on terminal at the bottom of your open PyCharm application (Should be to the right of "Version Control" and to the left of "Messages")
then run the following:
conda install numpy

Let me know if this helps!


text:
Q: PHP combining arsort & ksort I'm trying to sort an array by value descending keeping keys (arsort), but if the values are equal I want it also sorted in order of keys ascending (ksort).
I've been trying this:
ksort($array);
arsort($array);

But the ksort is not kept, and the keys get jumbled up again after the arsort.
E.g. if my input array in:
$array[0] = 4;
$array[1] = 2;
$array[2] = 3;
$array[3] = 1;
$array[4] = 4;

I want to sort it so it ends like this:
$array[0] = 4;
$array[4] = 4;
$array[2] = 3;
$array[1] = 2;
$array[3] = 1;

NOT like this:
$array[4] = 4;
$array[0] = 4;
$array[2] = 3;
$array[1] = 2;
$array[3] = 1;

But the previous order of the keys appears to be disturbed by arsort.

A: PHP dropped stable sorting (which guaranteed the ordering you wanted) in PHP 4.1:
https://bugs.php.net/bug.php?id=53341&edit=1
Here's a seemingly dupe question, with a code snippet, to work around it (basically: write your own sort function. Boo.):
Preserve key order (stable sort) when sorting with PHP's uasort

A: That's a pity, since it's not supported, here's a function I wrote for it:
function arksort($array)
    {
    arsort($array);
    $newarray=array();
    $temp=array();
    $on=current($array);
    foreach($array as $key => $val)
        {
        if ($val===$on) $temp[$key]=$val;
        else
            {
            ksort($temp);
            $newarray=$newarray+$temp;
            $temp=array();
            $on=$val;
            $temp[$key]=$val;
            }
        }
    ksort($temp);
    $newarray=$newarray+$temp;
    reset($newarray);
    return $newarray;
    }


text:
Q: How to share wired internet connection to wifi (non Adhoc)? I have a wired interconnection in my ubuntu laptop. I want to share this connection to my Nexus 7. I tried creating a Ad-hoc connection but N7 doesn't recognise ad-hoc wifi. So I found my old wireless router ( Beetel 450TC1 ) and connected both my laptop and N7. I ran a web server in my laptop and I am able to see it in N7. Now, How do I forward my wired internet connection to N7? I think I must run some proxy server to forward all requests to eth0 interface. Any ideas, how to set this up?

A: You need some packages and have to configure it:
1. HostAPD
2. DHCP
3. ip masquerading
To know how to configure these packages please read this article: http://techmites.com/laptop-wired-establish-wifi-in-ubuntu/


text:
Q: EXE's VERSION info not displaying in Properties dialog (Windows XP) I have built a Win32 console application using Visual Studio 6.0 in Windows XP. The EXE does have a VERSION resource. I can open the EXE and display the version information with Visual Studio or with other programs that read resources.
But, when I right-click on the EXE and ask for its Properties, no VERSION resource info is shown. Is that normal for a console application? All of my GUI applications show version info in Properties, no problem.
What am I missing here? Or is that some kind of Windows XP limitation? All suggestions welcome. Thanks!


text:
Q: javascript date format conversion I am using pikaday's datepicker. It gives me output "Fri Sep 20 2013". How can I convert this date into yyyy-mm-dd format and I also would want following date of this selected date and set that one to another element.
I tried this code
function formattedDate() {

    var fromdate = new Date(document.getElementById('datepicker').value);
        var dd = fromdate.getDate();
        var mm = fromdate.getMonth()+1; //January is 0!
        var yyyy = fromdate.getFullYear();
        if(dd < 10)
        {
            dd = '0'+ dd;
        }
        if(mm < 10)
        {
            mm = '0' + mm;
        }
        var fromdate1 = dd+'/'+mm+'/'+yyyy;
        fromdate.setDate(fromdate.getDate() + 2);
        document.getElementById('datepicker').value = fromdate1;
        var newdate = fromdate;
        document.getElementById('datepicker1').value = newdate;
//alert(newdate1);

}

But it doesn't work.

A: var date = new Date(dateString);
var year = date.getFullYear(), month = (date.getMonth() + 1), day = date.getDate();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;

var properlyFormatted = "" + year + month + day;

Or
var date = new Date(dateString);
var properlyFormatted = date.getFullYear() + ("0" + (date.getMonth() + 1)).slice(-2) + ("0" + date.getDate()).slice(-2);

A: Use momentjs — it's a library available for using in browser and node projects
In your case you should use this pattern:
moment().format("YYYY-mm-D");

And you can try it in console on momentjs's site:


text:
Q: Keyguard manager how to remove cancel button When using KeyguardManager, how do I remove the cancel button? There is a cancel button that appears on left side.
if(km.isKeyguardSecure()) {
            Intent i = km.createConfirmDeviceCredentialIntent("Authentication required", "password");
            startActivityForResult(i, CODE_AUTHENTICATION_VERIFICATION);
        }

  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK && requestCode==CODE_AUTHENTICATION_VERIFICATION)
        {
            Toast.makeText(this, "Success: Verified user's identity", Toast.LENGTH_SHORT).show();
            Session.setLock(false);
            startActivity(new Intent(this,WelcomeACtivity.class));
        }
}

A: @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK && requestCode==CODE_AUTHENTICATION_VERIFICATION)
        {
            Toast.makeText(this, "Success: Verified user's identity", Toast.LENGTH_SHORT).show();
            Session.setLock(false);

            startActivity(new Intent(context,WelcomeACtivity.class));

        }
        else if(resultCode == RESULT_CANCELED && requestCode == CODE_AUTHENTICATION_VERIFICATION)
        {
            finish();
        }
        else
        {
            Toast.makeText(this, "Failure: Unable to verify user's identity", Toast.LENGTH_SHORT).show();

        }
    }


text:
Q: Get temperature given pressure and enthalpy ThermodynamicData["Ammonia", "Enthalpy", {"Temperature" -> t,"Pressure" -> p}]

works fine, but how can I get temperature when pressure and enthalpy are given?

A: i suppose you can use standard numerical methods..
 h[t_?NumericQ, p_?NumericQ] :=
 QuantityMagnitude[
   ThermodynamicData["Ammonia",
    "Enthalpy", {"Temperature" -> Quantity[t, "Kelvins"],
     "Pressure" -> Quantity[p, "MegaPascals"]}]]

FindRoot[h[t,.4] == 19300, {t, 200}]

{t -> 199.982}


text:
Q: Performing custom actions on `scons -c` I have made a SCons builder that takes a Makefile file as a source and calls it to generate "things".
(Mainly it is a Makefile written by other libraries, so I don't have to choice to replace it with SCons).
So far, it works well but now I'd like to make the scons -c work as well.
My MakefileCallBuilder only has a dummy target as its target so scons -c won't really clean anything.
Is there a way of telling SCons that I want make clean or make distclean to be called upon cleaning ?

A: I have been pulling my hair out because of this exact problem. I finally created a solution that is kind of crude, but works. Here is the part of the SConstruct file which does cleaning:
import subprocess

...

# Call make to clean
if env.GetOption('clean'):
    subprocess.call(['make', 'clean'])

Basically, since Scons does not offer any way to call make clean, I get it done via Python's subprocess.call().


text:
Q: Dúvida SQL LEFT JOIN em uma tabela com valores nulos Atualmente executo uma query que retorna um grupo de dados utilizado depois em um report do power bi.
O que eu preciso é filtrar todos os registros que tenham a coluna Status A ou B, além desses resultados existem registros com essas colunas com Status Nulo, D ou E.
Pra buscar essa informação preciso de três tabelas, a tabela EC (tabela que nos retorna a chave principal dos registros), a tabela OV e a tabela OVI(essa terceira é a que provê esse status)
tab.EC - relaciona - tab.OV
tab.OV - relaciona - tab.OVI
Eu preciso trazer esse status como uma coluna para tratar no meu report, ou já na query tratar essa informação para ignorar os status A e B.
Tentei fazer da forma abaixo selecionando o código do escritório (que é a nossa relação com a tabela dos registros principais) e pegando a data máxima do registro da EC. O problema é que como é um LEFT JOIN depois de filtrado esse select, ele trata como NULL os registros que eram A ou B, e isso fica errado no resultado final para o objetivo da query porque precisamos também dos registros que originalmente eram NULL (alguns registros como mencionei acima tem o valor nulo realmente e devem ser considerados dessa forma).
Também já tentei agrupar pelo campo de Status, mas quando faço isso gera uma duplicidade em casos onde um item do EC já teve mais de um status registrado em relação com as tabelas OV e OVI.
LEFT JOIN (SELECT OISIDCLO,
                  Max(OITOPEDT) AS OITOPEDT
                  FROM   [DATABASE].OISSAOHT OV
                         LEFT JOIN [DATABASE].OITSAOIT OVI
                                ON OV.OISIDSOH = OVI.OITIDSOH
                                WHERE OVI.OITLCSTA != 'A' OR OVI.OITLCSTA != 'B'
                  GROUP  BY OISIDCLO) OV
              ON EC.OFDIDESC = OV.OISIDCLO

Edit:
Hoje eu fiz um teste especificando para pegar os nulos dentro da subquery, ainda não validei totalmente, mas tive um resultado diferente, estou atualizando a pergunta porque ainda não resolvi o problema, mas pode ser um caminho.
LEFT JOIN (SELECT OISIDCLO,
                  Max(OITOPEDT) AS OITOPEDT
                  FROM   [DATABASE].OISSAOHT OV
                         LEFT JOIN [DATABASE].OITSAOIT OVI
                                ON OV.OISIDSOH = OVI.OITIDSOH
                                **WHERE (
                                         OVI.OITLCSTA is null
                                      OR OVI.OITLCSTA != 'A'
                                      OR OVI.OITLCSTA != 'B'
                                      )**
                  GROUP  BY OISIDCLO) OV
              ON EC.OFDIDESC = OV.OISIDCLO

Edit2: Essa opção de is null, funcionou pra mim, o problema agora é em outro filtro, mas não tem relação com esse problema! Agradeço quem conseguiu enviar respostas, e quem teve tempo de ler aqui pra tentar me ajudar.

A: Olá, você está colocando esse "filtro" como um argumento do LEFT JOIN dessa forma, quando o status for "A" ou "B" ele retornará como NULL. Para ignorar esses status você deve fazer isso na cláusula WHERE:
LEFT JOIN (SELECT OISIDCLO,
              Max(OITOPEDT) AS OITOPEDT
              FROM   [DATABASE].OISSAOHT OV
                     LEFT JOIN [DATABASE].OITSAOIT OVI
                            ON OV.OISIDSOH = OVI.OITIDSOH
              WHERE OVI.OITLCSTA != 'A'
              AND OVI.OITLCSTA != 'B'
              GROUP  BY OISIDCLO) OV
          ON EC.OFDIDESC = OV.OISIDCLO

Espero ter ajudado!


text:
Q: Google App Script Only Pull Rows With Data I have a google sheet that is populated with changing data daily based off of today's date and what I would like to do is push every line that has data into a Slack channel daily on a time trigger. As you can see I started building this out making each cell its own variant, but when Row 3 doesn't have data it will still push a blank update into Slack like this:
I'm guessing that I need to add an IF somewhere in here, but not sure where. Here is the code:
 function createMeetingMessage(sheet) {
 var porow1 = "Bulk!A2";
 var OrderDaterow1 = "Bulk!K2";
 var OrderReqrow1 = "Bulk!J2";
 var Desrow1 = "Bulk!D2";
 var Vendorrow1 = "Bulk!E2";
 var ETArow1 = "Bulk!L2";
  var porow2 = "Bulk!A3";
 var OrderDaterow2 = "Bulk!K3";
 var OrderReqrow2 = "Bulk!J3";
 var Desrow2 = "Bulk!D3";
 var Vendorrow2 = "Bulk!E3";
 var ETArow2 = "Bulk!L3";
   var porow3 = "Bulk!A4";
 var OrderDaterow3 = "Bulk!K4";
 var OrderReqrow3 = "Bulk!J4";
 var Desrow3 = "Bulk!D4";
 var Vendorrow3 = "Bulk!E4";
 var ETArow3 = "Bulk!L4";

var message = "> *Today's Purchases*" +"\n"
+ "> *PO:* " +sheet.getRange(porow1).getValue() +"\n"
+ "> *Order Date:* " +sheet.getRange(OrderDaterow1).getValue() +"\n"
+ "> *Requested By:* " +sheet.getRange(OrderReqrow1).getValue() +"\n"
+ "> *Description:* " +sheet.getRange(Desrow1).getValue() +"\n"
+ "> *Vendor:* " +sheet.getRange(Vendorrow1).getValue() +"\n"
+ "> *ETA:* " +sheet.getRange(ETArow1).getValue() +"\n"
+"\n"
+ "> *PO:* " +sheet.getRange(porow2).getValue() +"\n"
+ "> *Order Date:* " +sheet.getRange(OrderDaterow2).getValue() +"\n"
+ "> *Requested By:* " +sheet.getRange(OrderReqrow2).getValue() +"\n"
+ "> *Description:* " +sheet.getRange(Desrow2).getValue() +"\n"
+ "> *Vendor:* " +sheet.getRange(Vendorrow2).getValue() +"\n"
+ "> *ETA:* " +sheet.getRange(ETArow2).getValue() +"\n"
+"\n"
+ "> *PO:* " +sheet.getRange(porow3).getValue() +"\n"
+ "> *Order Date:* " +sheet.getRange(OrderDaterow3).getValue() +"\n"
+ "> *Requested By:* " +sheet.getRange(OrderReqrow3).getValue() +"\n"
+ "> *Description:* " +sheet.getRange(Desrow3).getValue() +"\n"
+ "> *Vendor:* " +sheet.getRange(Vendorrow3).getValue() +"\n"
+ "> *ETA:* " +sheet.getRange(ETArow3).getValue() +"\n";

 return message;
}

function triggerSlackRequestPD(channel, msg) {
 var slackWebhook = "[SLACK WEBHOOK]";
  var payload = { "channel": channel, "text": msg, "link_names": 1, "username": "Procurementron", "icon_emoji": ":robot_face:" };
 var options = { "method": "post", "contentType": "application/json", "muteHttpExceptions": true, "payload": JSON.stringify(payload) };

Logger.log(UrlFetchApp.fetch(slackWebhook, options));
}

function notifySlackChannelOfFacilitatorAndNoteTaker() {
 var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Bulk");
 if (!sheet.getRange("B2").getValue()) return;
var channel = getChannel();

var msg = createMeetingMessage(sheet);
 triggerSlackRequestPD(channel, msg);
}

function isTest() {
 return false;
}

function getChannel() {
 if(isTest()) {
 return "[SLACK CHANNEL]";
 } else {
 return "[SLACK CHANNEL]";
 }
}

Open to any and all suggestions. Ideally, there was a like var get.alldata in a column so that I don't have to make a variant for each cell. Thanks!

A: *

*When porow3, OrderDaterow3, OrderReqrow3, Desrow3, Vendorrow3, ETArow3 are empty, you don't want to including them in message.

If my understanding is correct, how about this modification? I think that there are several solutions for your situation. So please think of this as one of them.
Modification points:

*

*I think that in your script, it is required to be modified createMeetingMessage().

*At createMeetingMessage(), all values are the constant ranges, and all labels of each message are also the same.

*

*I think that these situation can be used to modify your script.

*In your script, you retrieve the values using getValue().

*

*Retrieve all values using getValues().

When above points are reflected to your script, the script is as follows.
Modified script:
Please modify your createMeetingMessage() to the following script, and try it.
function createMeetingMessage(sheet) {
  var values = sheet.getRange("Bulk!A2:L4").getValues(); // Please modify this range, if you want to add rows.
  var message = values.reduce(function(s, e) {
    var porow, OrderDaterow, OrderReqrow, Desrow, Vendorrow, ETArow, _,
    [porow, _, _, Desrow, Vendorrow, _, _, _, _, OrderReqrow, OrderDaterow, ETArow] = e;
    if (porow && OrderDaterow && OrderReqrow && Desrow && Vendorrow && ETArow) {
      s += "> *PO:* " + porow +"\n"
      + "> *Order Date:* " + OrderDaterow +"\n"
      + "> *Requested By:* " + OrderReqrow +"\n"
      + "> *Description:* " + Desrow +"\n"
      + "> *Vendor:* " + Vendorrow +"\n"
      + "> *ETA:* " + ETArow +"\n"
      +"\n";
    }
    return s;
  }, "> *Today's Purchases*" +"\n");
  return message;
}

Note:

*

*In this modified script, the all values of porow, OrderDaterow, OrderReqrow, Desrow, Vendorrow, ETArow of each row are existing, they are included in the message.

*

*If you want to modify it, please modigy this.

*If you want to add rows, please modify Bulk!A2:L4 of var values = sheet.getRange("Bulk!A2:L4").getValues().

References:

*

*getValue()

*getValues()

*reduce()


text:
Q: Why does python max('a', 5) return the string value? Tracing back a ValueError: cannot convert float NaN to integer I found out that the line:
max('a', 5)
max(5, 'a')

will return a instead of 5.
In the above case I used the example string a but in my actual case the string is a NaN (the result of a fitting process that failed to converge).
What is the rationale behind this behaviour? Why doesn't python recognize automatically that there's a string there and that it should return the number?
Even more curious is that min() does work as expected since:
min('a', 5)
min(5, 'a')

returns 5.

A: In CPython 2.x strings are always greater than numbers, that's why you see those behaviors.
OTOH, I don't get why you think that 5 is "obviously" greater than "a"... Values of different types are comparable just for convenience (e.g. if you are building an RB tree with eterogeneous keys you want everything to be comparable), and such comparisons do define a strict weak ordering, but inter-type comparisons are not intended to be sensible in any way (how do you compare a number to a string or an object?), just coherent.

A: In Python 2, numeric values always sort before strings and almost all other types:
>>> sorted(['a', 5])
[5, 'a']

Numbers then, are considered smaller than strings. When using max(), that means the string is picked over a number.
That numbers are smaller is an arbitrary implementation choice. See the Comparisons documentation:

The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily.

Bold emphasis mine.
Python 2 tried real hard to make heterogenous types sortable, which has caused a lot of hard to debug problems, such as programmers trying to compare integers with strings and getting unexpected results. Python 3 corrected this mistake; you'll get a TypeError instead:
>>> max(5, 'a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()

I've written elsewhere about the ordering rules, and even re-implemented the Python 2 rules for Python 3, if you really wanted those back.


text:
Q: Does Scala allow overloaded constructor to have statements other than 'this'? I have a case class in Scala whose primary constructor takes "friends" as comma delimited string.  The secondary(overloaded) constructor takes "friends" as Array[String] and calls the primary constructor.  For some reason, "friends" in the primary constructor has to be a String and in the overloaded constructor, it has to be Array[String] .
In the secondary constructor, I think I need to check if friends is null before calling mkString, I tried to use "if" statment to check but it doesn't seem to compile and recoganize friends as an Array, so it doesn't allow me to call isEmpty, so does scala have similar thing to "? :" operator so that I can check friends within the calling of primary constructor?
 case class Person(val friends: String)
 {
      def this(friends: Array[String]) =
      {
          if ( !friends.isEmpty)
            // doesn't compile, error message: 'this' expected but 'if' found
              this(friends.mkString(",") // throw NULL pointer exception
              // can I do "this((friends.isEmpty)?"":friends.mkString(","))" here ?
       }
 }

A: if statement should work: this(if(friends == null) "" else friends.mkString(","))
A more idiomatic way in scala would be to use Option:
this(Option(friends).getOrElse(Array.empty[String]).mkString(","))
As for "having statements other than this", you can have them, but this must be the first thing you do in constructor. It is the same way in java as well.

A: The if-else conditional expression in Scala yields a value, unlike other traditional languages, such as Java. You still have to make sure that this is the first expression in your secondary constructor. It would look like this:
def this(friends: Array[String]) =
    this(if (friends != null && !friends.isEmpty) friends.mkString(",") else "")

A different approach could be to either accept and Option[Array[String]] or wrap it yourself with one:
def this(friends: Option[Array[String]]) =
    this(friends.getOrElse(Array.empty[String]).mkString(","))


text:
Q: Converting time from different timezone with daylight savings included I have process that accepts datetime value with timezone as a string (data comes from outside system). I need to translate this datetime to what the time would have been at the local machines timezone.
Example code:
string cetId = "Central European Standard Time";
if (timeZone == "CET")
{
    TimeZoneInfo cetZone = TimeZoneInfo.FindSystemTimeZoneById(cetId);
    returnDateTime = TimeZoneInfo.ConvertTime(statusDateTime, cetZone, TimeZoneInfo.Local);
}
else if (timeZone == "CEST")
{
    TimeZoneInfo cestZone = TimeZoneInfo.FindSystemTimeZoneById(cetId);
    returnDateTime = TimeZoneInfo.ConvertTime(statusDateTime, cestZone, TimeZoneInfo.Local);
}

Do I need to do anything specific if the time is CEST (central european summer time) instead of CET (central european time) or does .net TimeZoneInfo object handle that scenario?

A: You should be fine.
You are telling ConvertTime what both time zones (source and target) are.
Do you have a specific problem with this or are you just asking for confirmation?

A: From TimeZoneInfo.ConvertTime()
The value of the Kind property of the dateTime parameter must correspond to the sourceTimeZone parameter, as the following table shows.

Just want to add that you need to watch out for the 'Kind' property of your StatusDateTime. In your case, it HAS to be 'Unspecified'. Check out the 'Remarks' section

A: I created a library a while back to encapsulate these kinds of transforms:
https://github.com/b9chris/TimeZoneInfoLib.Net/blob/master/TimeZoneInfoLib/TimeZone/UtcTimeZone.cs
Might be useful to you, or you may just want to pick it over to double-check your code. One of the things it encapsulates is @Brian's caveat - so it has explicit method names relating to the .Kind property, that throw useful exceptions if the .Kind is wrong. It also takes a little bit of the grunt work out of getting useful/common/daylight time names and abbreviations:
https://github.com/b9chris/TimeZoneInfoLib.Net/blob/master/TimeZoneInfoLib/TimeZone/TimeZoneShortNameMap.cs


text:
Q: Android: If function runs with no user unique ID and user isn't authenticated into Firebase I'm trying to check for errors in my log in screen which is connected to Firebase, the OnCompleteListener that i use checks if:
1) The user has already signed up or not
2) If the user has given me information in my database
Whenever a user inputs an Email that isn't authenticated it will tell him to give information as well(Checking if a unique id exists for a null), it shouldn't happen though or in other words, Why does the if(task.isComplete() && !task.isSuccessful())
Run when there is no Unique ID and no User
Here's the OnCompleteListener Code, Ignore the OnSuccesslistener one
Task<AuthResult> authResultTask = firebaseAuth.signInWithEmailAndPassword(Email, Password)
    // if login is complete
    .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            // dismisses progressbar and checks if the users has already given Essential Information,
            // If not it will take him to the essential information activity
            progressDialog.dismiss();

            if(task.isComplete() && !task.isSuccessful()){
                // Checks if user has submitted information in the Essential Information activity
                // Takes the Unique ID(if it is present if not it will tell him to sign up or invalid email)
                // asks the firebase database if he has given information to the database
                FirebaseUser user = firebaseAuth.getCurrentUser();
                String UserUID = user.getUid();
                reference.child("Users").child(UserUID).addValueEventListener(new ValueEventListener() {

                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        // User exists
                        if (dataSnapshot.exists()) {
                            //Displays Toast telling user that their information is saved in the database
                            Toast.makeText(LogInActivity.this, "You have data in our database ", Toast.LENGTH_SHORT).show();
                        }
                        //User doesn't have information in the database
                        else {
                            // Displays Toast telling user he/she needs to sign in into the firebase database
                            // User goes to UserInformationActivity to give his/her information
                            Toast.makeText(LogInActivity.this, "You need to give Essential Information", Toast.LENGTH_SHORT).show();

                            // 3 second delay
                            final Handler handler = new Handler();
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    // Goes to UserInformationActivity
                                    Intent GoToUserInformation = new Intent(LogInActivity.this, UserInformationActivity.class);
                                    LogInActivity.this.startActivity(GoToUserInformation);
                                }
                            }, 3000);
                        }
                    }

                    // if the checking got cancelled, likability of that happening is small
                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }

                });
            }

            if (!task.isSuccessful()) {
                try {
                    throw task.getException();
                } catch(FirebaseAuthInvalidUserException e) {
                    Toast.makeText(LogInActivity.this, "Invalid email, You need to sign up first", Toast.LENGTH_SHORT).show();
                    // 3 second delay
                    final Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            // Goes to UserInformationActivity
                            Intent Signup = new Intent(LogInActivity.this, SignupActivity.class);
                            LogInActivity.this.startActivity(Signup);
                        }
                    }, 3000);
                } catch(Exception e) {
                    Toast.makeText(LogInActivity.this, "", Toast.LENGTH_SHORT).show();
                    Log.e("Exception", e.getMessage());
                }
            }

        }

    })
    .addOnSuccessListener(new OnSuccessListener<AuthResult>() {
        @Override
        public void onSuccess(AuthResult authResult) {
            Toast.makeText(LogInActivity.this, "SuccesListener working", Toast.LENGTH_SHORT).show();
        }
    });


text:
Q: How to create Android Database application? I am new to Databases and do not know if this would be the best way to do what I want to achieve. I want to create a custom list of restaurants around me, then search them, and sort them on ranking, title, or location.
Would I need to create a database for this? I technically could use a text file and Arrays but I feel like this is very inefficient. I would need a Node to contain the following data: Name of Establishment, Address, Phone Number, Ranking (Based of Our Ranking System).
How should I go about doing this?

A: Yes, you definitely want to use a database. If you use a database local to the phone, you need to use an SQLite database. Here is a good place to start.
If you want a database that is preloaded in the phone, put it in your assets folder. Here is an example of a database helper class with the database packaged with the phone:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBaseHelper extends SQLiteOpenHelper{

private static final String TAG = "DataBaseHelper";

//The Androids default system path of your application database.
private static String DB_PATH = "/data/data/yourpackage/databases/";

private static String DB_NAME = "DatabaseName";

public SQLiteDatabase myDataBase;

private final Context myContext;

    /**
     * Constructor
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     * @param context
     */
    public DataBaseHelper(Context context) {

        super(context, DB_NAME, null, 1);
        this.myContext = context;
    }

  /**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
    public void createDataBase() throws IOException{

        boolean dbExist = checkDataBase();

        if(dbExist){
            //do nothing - database already exist
        }else{

            //By calling this method and empty database will be created into the default system path
               //of your application so we are gonna be able to overwrite that database with our database.
            this.getWritableDatabase();

            try {

                copyDataBase();

            } catch (IOException e) {

                throw new Error("Error copying database");

            }
        }

    }

    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesnt
     */
    private boolean checkDataBase(){

        SQLiteDatabase checkDB = null;

        try{
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

        }catch(SQLiteException e){

            //database doest exist yet.

        }

        if(checkDB != null){

            checkDB.close();

        }

        return checkDB != null ? true : false;
    }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException{

        //Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);

        Log.d(TAG, "found the database");
        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;

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

        //transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[2048];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

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

    }

    public void openDataBase() throws SQLException{

        //Open the database
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
    }

    @Override
    public synchronized void close() {

            if(myDataBase != null)
                myDataBase.close();

            super.close();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

        // Add your public helper methods to access and get content from the database.
       // You could return cursors by doing "return myDataBase.query(....)" so itd be easy
       // to you to create adapters for your views.

A: A SQLite database would be an excellent way to accomplish your application goals. Based on what you said, a single table called "Restaurants" containing 5 fields: _id, Name, Address, Phone, Rank would do the trick.
The SQLite SQL documentation is located here: http://www.sqlite.org/lang.html . Some of the commands you'll need to be familiar with are CREATE TABLE, INSERT, UPDATE and SELECT. Sqlite for Android is a well-documented standard found across the web. You should have no trouble finding examples of how to accomplish your task.
Remember to close any database objects that you create else, you'll create a leak.
Good luck!

A: What you want to do is create a Web Service, this lives in the "cloud" on the Internets somewhere. Then you have your mobile app periodically contact the web service and request restaurant data perhaps based on the users current location, so the app passes the gps coordinates to the web service and the Web Service checks its database for restaurants within X distance of that location, then the Web Service returns the list to the app in a format such as Json or XML, the App parses this info and displays it to the user.
Ideally you would also have a database on the phone that would store results on the device this reduces the amount of requests you have to pull from the server, saving on battery, data and server resources. This gets a little complicated as you have to decide what to ask for intelligently and the server has to decide what to send you.
There was a Google I/O talk on how to do this.
http://www.youtube.com/watch?v=xHXn3Kg2IQE


text:
Q: Simple ludo game implementation with java threads I'm new with Java threads and I am having a few problems. I'm trying to make a simple ludo game, where each player makes their turn in a new thread. While one player is performing their turn the other threads must wait() until notified and the next player will start his turn. These threads must be synchronised so that only one thread can manipulate shared data at one time. I've implemented some basic logic but can't decide where to create the threads and if the thread logic I've implemented will work. Any help is appreciated!
Edit: I remade some parts of the code, but now I get "current thread is not owner" error after the first call of finishTurn().
Code:
Main.java:
public class Main {
    public static void main(String[] args) {
        Game game = new Game();
        game.init();
        game.run();
    }
}

Game.java:
public class Game implements Runnable {
    private List<Player> players;
    private List<Player> fields;
    private int players_finished;
    private Player winner;

    public Game() {
        this.players = new ArrayList<>();
        this.fields = new ArrayList<>();
        this.players_finished = 0;
        this.winner = null;
    }

    public void init()
    {
        System.out.println("Game has started!");
        players.add(new Player("Magnum", this));
        players.add(new Player("Felix", this));
        players.add(new Player("Alex", this));
        players.add(new Player("Sandra", this));

        for(int i = 0; i < 20; i++) {
            fields.add(i, null);
        }

        for(int i = 0; i < 20; i++) { // put players' 5 fields away from each other
            if(i % 5 == 0)
            {
                fields.set(i, players.get((int)i / 5));
            }
        }
    }

    @Override
    public void run()
    {
        List<Thread> threads = new ArrayList<>();
        for(int i = 0; i < 4; i++) {
            threads.add(new Thread(players.get(i)));
            threads.get(i).start();
        }
        System.out.println("Game has started!");

        finishTurn(players.get(3));
    }

    void finishTurn(Player player)
    {
        System.out.println(player + " has finished his turn!");
        int i;
        for(i = 0; i < players.size(); i++) {
            if(players.get(i) == player) {
                break;
            }
        }
        if(i == (players.size() - 1)) {
            players.get(0).notify();
        }
        else {
            players.get(i+1).notify();
        }
    }
}

Player.java:
public class Player implements Runnable {
    String name;
    Game game;

    public Player(String name, Game game) {
        this.name = name;
        this.game = game;
    }

    @Override
    public void run() {
        synchronized (this) {
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("Player's turn has been started!");
        // do other stuff
        game.finishTurn(this);
    }

    @Override
    public String toString() {
        return name;
    }
}


text:
Q: repetitive treatment on spark streaming I'm  new to Spark, I want to make a treatment on files in streaming.
I have files csv which arrive non-stop:
Example csv file:
world world
count world
world earth
count world

and I want to do two treatment on them :
the first treatment is for a result like this :
(world,2,2) // word is twice repeated for the first column and distinct (world,earth) for second therefore (2,2)
(count,2,1) // word is twice repeated for the first column and not distinct (world,world) for second therefore (2,1)

the second result
I want to get that result after each hour.in our example:
(world,1) // 1=2/2
(count,2) //2=2/1

this is my code :
val conf = new SparkConf()
    .setAppName("File Count")
    .setMaster("local[2]")
val sc = new SparkContext(conf)
val ssc = new StreamingContext(sc, Seconds(10m))
  val file = ssc.textFileStream("hdfs://192.168.1.31:8020/user/sparkStreaming/input")
    var result = file.map(x => (x.split(" ")(0)+";"+x.split(" ")(1), 1)).reduceByKey((x,y) => x+y)
  val window = result.reduceByKeyAndWindow((a:Int,b:Int) => (a + b), Seconds(60), Seconds(20))
  val result1 = window.map(x => x.toString )
  val result2 = result1.map(line => line.split(";")(0)+","+line.split(",")(1))
  val result3 = result2.map(line => line.substring(1, line.length-1))
  val result4 = result3.map(line => (line.split(",")(0),line.split(",")(1).toInt ) )
  val result5 = result4.reduceByKey((x,y) => x+y )
  val result6 = result3.map(line => (line.split(",")(0), 1 ))
  val result7 = result6.reduceByKey((x,y) => x+y )
  val result8 = result7.join(result5) // (world,2,2)
  val finalResult = result8.mapValues(x => x._1.toFloat /  x._2  ) // (world,1), I want this result after every one hour
  ssc.start()
  ssc.awaitTermination()

Thanks in Advance!!!


text:
Q: Lua and the white spaces of the OS. How to solve? I'm trying to execute a command with io.popen in Lua, but the path contains white spaces. I've tested with \\, combinations of  \"\', and so on. How to solve this, because the command always returns "C:\Program" not recognized....

A: See:Why won't applications in Program Files run using os.execute in lua?
the [[ ]]  method works well for me.

A: You might want to try
io.popen([[C:/Program Files (x86)/Microsoft Visual Studio 9.0/VC/vcpackages/vcbuild.exe]], "r")

Note that you were calling the function with one argument that looked like this:
"C:/.../vcbuild.exe", "r"

A: local exe_path = '"C:/Program Files (x86)/Microsoft Visual Studio 9.0/VC/vcpackages/vcbuild.exe"'

io.popen(exe_path, "r")


text:
Q: Как изменить выражение виртуального столбца по которому секционирована таблица? Ошибка: ORA-54019 Есть таблица, которая секционирована по виртуальному столбцу, требуется изменить выражение для этого виртуального столбца, но, по-видимому, это невозможно сделать тем способом, который пробую:
ALTER TABLE MY_TABLE
MODIFY VIRTUAL_COLUMN
GENERATED ALWAYS AS (TO_DATE(SUBSTR(SOME_COLUMN, 4, 8), 'yyyymmdd'))

ORA-54019: Невозможно изменить выражение виртуального столбца, т.к. этот столбец является столбцом секционирования

Как можно изменить этот виртуальный столбец?

Свободный перевод вопроса HHow to solve ORA-54019: Virtual column expression cannot be changed because it is a partitioning column? от участника @Dinu Nicolae

A: Если виртуальный столбец является частью ключа секционирования, то его выражением нельзя изменить.
Если требуется его изменить так, чтобы можно было также изменить схему секционирования, то надо:

*

*Добавить новый виртуальный столбец с нужным выражением.

*Изменить схему секционирования, чтобы использовать новый виртуальный столбец.

Если версия 18c или выше, то можно сделать с ALTER TABLE:
create table t (d date, v number as (to_number (to_char (d, 'yyyymmdd' ))))
    partition by range (v) (
        partition p0 values less than (20200101))
/
alter table t
  modify v number as (to_number (to_char (d, 'yyyymm')))
/
ORA-54019: Невозможно изменить выражение виртуального столбца,
           т.к. этот столбец является столбцом секционирования
54019. 0000 -  "Virtual column expression cannot be changed because it is a partitioning column"
*Cause:    Attempted to modify the expression of a virtual column that was
           also a partitioning column.
*Action:   This is not supported.

alter table t
  add v2 number as (to_number (to_char (d, 'yyyymm')))
/
alter table t
    modify partition by range (v2) (
        partition p0 values less than (202001)
    ) online
/
select column_name
from user_part_key_columnswhere name = 'T';

COLUMN_NAME
----------------
V2

Для более старых версий лучше использовать пакет DBMS_REDEFINITION, чтобы минимизировать время простоя. Например, как показано в этой статье.

Свободный перевод ответа от участника @Chris Saxon