text:
Q: Spring @Transactional I'm trying to put together a bare-bones minimalist JUnit test for a system using Spring @Transactional annotations, and not having much success.
I'm creating two instances with the same value for a column that has a unique constraint.  If the two instance creations happen to be in different transactions, I expect that the first will commit and the second will throw an exception, leading to one row -- and I see that happening.  If the two inserts happen in the same Transaction, I expect both to be rolled back as an atomic unit, which I'm not seeing.  I'm sure that there's a configuration issue somewhere, but I've not had much luck identifying it.
For the test I have a bean (ContextTestHelperImpl / ContextTestHelper) with methods to create either one or two instances.  Each has a Propagation.REQUIRES_NEW annotation on the method:
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW,
        rollbackFor = {ContextDuplicationException.class})
public Foo createOneFoo(int val) throws ContextDuplicationException {
    try {
        return fooDAO.createFoo(val);
    } catch (Throwable th) {
        throw new ContextDuplicationException(th);
    }
}

@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW,
        rollbackFor = {ContextDuplicationException.class})
public Foo[] createTwoFoos(int val) throws ContextDuplicationException {
    try {
        return new Foo[] { fooDAO.createFoo(val), fooDAO.createFoo(val) };
    } catch (Throwable th) {
        throw new ContextDuplicationException(th);
    }
}

I have one JUnit test (ContextTest) which calls the first method twice:
public void dupTestTwoTransactions() {
    contextTestHelper.deleteAllFoo();
    Assert.assertEquals(0, contextTestHelper.getCountOfFoo());

    boolean hadException = false;
    try {
        contextTestHelper.createOneFoo(DUPLICATE_VALUE);
    } catch (ContextDuplicationException th) {
        hadException = true;
        System.out.println("[ContextTest][dupTestTwoTransactions] UNEXPECTED ERROR: " + th);
        th.printStackTrace();
    }
    Assert.assertEquals(hadException, false);
    Assert.assertEquals(1, contextTestHelper.getCountOfFoo());

    try {
      contextTestHelper.createOneFoo(DUPLICATE_VALUE);
    } catch (ContextDuplicationException th) {
        hadException = true;
    }
    Assert.assertEquals(hadException, true);
    Assert.assertEquals(1, contextTestHelper.getCountOfFoo());
}

This works as expected.  The first call doesn't throw an exception; the second call does.  At the end of it all, there's one row in the Foo table.
I have a second JUnit test in the same class which calls the latter method once:
@Test
public void dupTestOneTransaction() {
    contextTestHelper.deleteAllFoo();
    Assert.assertEquals(0, contextTestHelper.getCountOfFoo());

    boolean hadException = false;
    try {
      contextTestHelper.createTwoFoos(DUPLICATE_VALUE);
    } catch (ContextDuplicationException th) {
        hadException = true;
    }
    Assert.assertEquals(hadException, true);
    Assert.assertEquals(0, contextTestHelper.getCountOfFoo());
}

This second test fails on the final assertion -- the count of Foo instances is 1, while I'm expecting 0.
I have a little bit of shenanigans going on with the data source setup because we're trying to use a JNDI lookup for when the code runs under JBoss.  As a result, JUnit needs to set up the JNDI lookup behind the scenes (ContextTest.java):
@BeforeClass
public static void setUpClass() throws NamingException {
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-test.xml");
    DataSource testDataSource = (DataSource) context.getBean("testDataSource");
    SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
    builder.bind("java:comp/env/jdbc/dataSource", testDataSource);
    builder.activate();
}

Here is my spring-test.xml file which in NetBeans is set up in the Test Packages' default package:
<?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:tx="http://www.springframework.org/schema/tx"
    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/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:property-placeholder location="user-specific.properties"/>

<bean id="testDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName"><value>${db.driver.class}</value></property>
    <property name="url"><value>${db.url}</value></property>
    <property name="username"><value>${db.user}</value></property>
    <property name="password"><value>${db.password}</value></property>
</bean>
</beans>

Since the first test works, I'm clearly able to connect to the database, so I don't think there's any particular problem here.
Here's applicationContext.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
       http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd"
        default-autowire="byName" >

    <context:annotation-config />
    <context:component-scan base-package="com.xyzzy" />
    <tx:annotation-driven transaction-manager="transactionManager" />

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
           <value>classpath:user-specific.properties</value>
        </property>
    </bean>

    <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/dataSource"/>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="fooDAO" class="com.xyzzy.FooDAOImpl" />

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource"><ref local="dataSource"/></property>
        <property name="packagesToScan" value="com.xyzzy" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${db.dialect}</prop>
                <prop key="hibernate.show_sql">${db.show_sql}</prop>
                <prop key="hibernate.hbm2ddl.auto">${db.hbm2ddl.auto}</prop>
            </props>
        </property>
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="databasePlatform" value="${db.dialect}"/>
                <property name="generateDdl" value="true"/>
                <property name="showSql" value="true"/>

            </bean>
        </property>
        <property name="packagesToScan" value="com.xyzzy" />
    </bean>
</beans>

All of the not-solely-for-testing classes (Foo, FooDAO, FooDAOImpl) are in the package com.xyzzy, and all of the testing ones (ContextTest, ContextTestHelper, ContextTestHelperImpl, ContextDuplicationException) are in com.xyzzy.test.
There are no @Transactional annotations on Foo, FooDAO or FooDAOImpl.  ContextTestHelperImpl is the only one specifying Transaction boundaries.
Any suggestions for how to fix this so that it behaves as it should?  (Is there something wrong with my choice of dataSource class, or transactionManager?  Are some of my settings in applicationContext.xml inconsistent or redundant?)
UPDATE:
DAO implementation class:
@Repository("FooDAO")
public class FooDAOImpl implements FooDAO {
    private HibernateTemplate hibernateTemplate;

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.hibernateTemplate = new HibernateTemplate(sessionFactory);
    }

    @Override
    public Foo createFoo(int val) {
        Foo foo = new Foo();
        foo.setVal(val);
        saveFoo(foo);
        return foo;
    }

    void saveFoo(Foo foo) {
        hibernateTemplate.save(foo);
    }

    [... and many similar methods ...]

I also tried it with Propagation.REQUIRED (read somewhere that it will cause an exception early on if there's not a Transaction associated with the thread), but that does not change its behavior.

A: I believe you have have 2 tests in a class. You are assuming those tests are run sequentially. Your are expecting an exact record count of either 1 or 0. The tests are run in parallel, thus conflicting with your expected result.
Change the logic so that each test uses it's own unique values (for inserts). Instead of comparing a record count based on select all (no criteria). Select from the database with criteria (add a where clause).
To summarize, the test runner is running the tests in parallel. You need to take that in to account and segregate test cases. Use unique values in each test case.
Hope that helps.


text:
Q: How to solve the Richard differential equation? (analytical solution) I would like to solve the Richard differential equation, i.e. getting the the generalised logistic function. I tried to calculate it,
$$
\frac{dy}{dt} = \beta y \biggl( 1 - \biggl( \frac{y}{L} \biggr)^a \biggr)
$$
getting:
$$
\beta (t - t_0) = \int \frac{dy}{y\big(1-\big(\frac{y}{L}\big)^a\big)}
$$
but I am stuck at that integral. Any idea how to solve it? Thanks!

A: Hint.
$$
\frac{dy}{y\left(1-\left(\frac yL\right)^a\right)} = \frac{dy}{y}+\frac{\left(\frac{y}{L}\right)^{a-1}dy}{L \left(1-\left(\frac{y}{L}\right)^a\right)}
$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: understanding how nested functions work in javascript I want to understand how nested functions work for example
function outer(){
  console.log("Hello from outer function")
  function inner(){
    console.log("Hello from inner function")
  }
}

I want to understand what happens when i call outer(), how can i call the inner function, what is the execution context for inner function,

A: As you have not called inner() anywhere in the outer() function so that is why inner() is not getting called by default.
JavaScript will automatically allocate memory when values are initially declared. There is a link where you can read about memory management in JS
You cannot call inner() from outside. Once outer() finishes executing inner() will be garbage collected, since there is no other references to it.

function outer(){
  console.log("Hello from outer function")
  inner();
  function inner(){
    console.log("Hello from inner function")
  }
}

outer();

Using a closure way:

function outer() {
  var name = 'StackOverflow';
  function inner() {
    console.log("I am in Inner function at " + name);
  }
  return inner;
}

var outerfunction = outer();
outerfunction();

But if you see we are calling inner() in the outer function indirectly.

A: I think you mean this syntax:
functionName()();

this is syntax happen when a function return another function. like the code blow:
function f1(value1) {
    return function f2(value2) {
        return value1 + value2;
    };
}


text:
Q: How can my ScriptableObjects have a SerializeField reference to a Script? Each enemy in my game is a Scriptable Object (Enemy1, Enemy2, etc). Each enemy also has its own unique script to determine how battles go (BattleEvent1, BattleEvent2, etc)
The way my logic currently works is:

*

*BattleSystem component has all BattleEvents attached to it.

*When battle starts, check the name of the current Enemy, and use that string reference to pick which BattleEvent to run (LOTS of if statements).

But this is bad because it's all string references, so I can't easily ensure that each enemy has a BattleEvent, and there's a lot of if/else statements.
What I wanted to do was attach each BattleEvent script to its respective Enemy Scriptable Object.

But I'm not able to drag the scripts in that Battle Event SerializeField there.
I would ideally like my logic to work like:

*

*BattleSystem loads the enemy, and just checks the Enemy.BattleEvent to load the proper script.

Since I can't attach scripts to the SOs, I can't get this to work. Is there any way I can achieve a logic flow like this?


text:
Q: IOS - sync events from my app to native calendrer I have an ios app -built with react native- where among other things users can view a calendar of events coming from the API, I want to periodically sync these events to a native calendar as well so even when the user does not use the app it can get reminders of these events.
What I've considered:
1- Sync these events every time the user opens that app. which does not meet the complete requirements.
2- Run a background task to get events from the API and sync it to the native calendar. this works on the android side but not on IOS if the app is terminated.
3- Implement CalDav API but my app uses SSO to login and I'm not sure how to make this work with the username/password auth of CalDav.
Is there a better way to do this?


text:
Q: Any event afterPop()? not ionViewDidLeave() in Ionic2 Is there an event that fires afterPop() in Ionic2? Because in my case the ionViewWiillLeave does not serve me.
I have a Page1 that pushes Page2 and sends it parameters.
This Page2 has an array with a binding to his template. If I do pop() and then enter otherwise to Page2, double the contents of the array because it seems to be not automatically cleaned when exiting.
Then I solved it by making an array.lenght = 0 inside ionViewWillLeave ().
This works fine if I navigate between Page1 and Page2, since the array is emptied out of Page2 and sent back from Page1 if I re-enter.
The problem with this is that I actually have a third Page, which is below Page2.
The scheme would be this:
Page 1 -------------------> Page 2 -----------------> Page 3
With parameters ------ With array----------------

When I navigate from Page2 to Page3, ionViewWillLeave() is executed and the array is cleaned. Then when we go back (from Page3 to Page2), the array is empty because obviously Page3 does not return the contents of the vector as it does Page1. And so I have an empty Page2 template.
For this same thing I would need an event to run only after pop, to clean the array only when pop() is made from Page2, and it will not run whenever it is going to quit page hint.
Thank's so much in advance!
Ivan.


text:
Q: How to ignore empty string in list object? I have list object like below
0:""
1:""
3:"tag1"
4:"tag2

This is my question how to ignore empty value.I need a result like the  below.
0:"tag1"
1:"tag2

Thanks for help me.

A: One naive solution could be:

const obj = {
  0: "",
  1: "",
  2: "tag1",
  3: "tag2"
};

const newObj = Object.fromEntries(
  Object.entries(obj).filter(([k, v]) => v)
);

Object.entries turns an object into an array of keys and values.
For example
Object.entries(obj)

becomes
[
  [
    "0",
    ""
  ],
  [
    "1",
    ""
  ],
  [
    "2",
    "tag1"
  ],
  [
    "3",
    "tag2"
  ]
]

which is then filtered by whether the value is "truthy"
.filter(([k,v]) => v))

and finally turned back into an object
Object.fromEntries

A: If that is an array, you can use filter.

let o = ["","",,"tag1","tag2"];
let res = o.filter(Boolean); // or o.filter(x => x);
console.log(res);

To be more precise, you could use:
let res = o.filter(x => x !== '');


text:
Q: ASP.NET mvc detect clientside changes In my application I want a customer to not press submit when he didn't change values in a specific form. I can do this serverside and add a viewmodelerror to the modelstate. But is there a way to do this also clientside with javascript? I searched for it, but couldn't find it.

A: You can set a javascript variable if the form is edited.
A simple way of doing this would be to listen to the change event on input fields:
var isChanged = false;
$('input,select,textarea').change(function() {
  isChanged = true;
});

And then check for isChanged before submitting.
This approach doesn't deal with values being changed back to the original value though.
If you need to address that scenario, you would need to keep the form state in a javascript object and compare it with that.
You could add this to avoid the user to leave the page if the form has changed:
$(window).bind('beforeunload', function() {
  if (isChanged) {
    return 'You have changed the form, are you sure?';
  } else {
    return undefined;
  }
});

A: Not sure what you asking? Are you talking about client side validation? in this case you could use MVC Validation or a javascript library like jquery and use a validation plugin

A: What is the client supposed to change?
If, for example. it's just the value of a text field you could save the original value in the document ready jquery event and when hitting the submit button run a javascript function that checks if the value has changed.
If you have more complex input fields you can still use this mechanism to save the original and check on submit trough javascript.


text:
Q: Add rich text format functionality to django TextField I have a django model which contains a description field:
class Product(models.Model):
    name = models.CharField(max_length="125")
    description = models.TextField()

class ProductForm(ModelForm):
    class Meta:
        model = Product
    def __init__(self, *args, **kwargs):
        super(ProductForm, self).__init__(*args, **kwargs)
        self.fields['description'].widget.attrs = { 'placeholder':'Description', 'rows':'10'}

I am rendering it as  below

     {{form.name}}
     {{form.description | linebreaks}}

So with the above filter linebreaks I am able to get the data as line formatting, but now I want to give a url(www.google.co.in) in the description field, and it should be a clickable on the front end in the product detail page
How to add the rich text formatting to django description field on front end?

A: Another way could be adding some html in the description field
your link

and make it accessible on the front-end with the safe tag:
{{form.description | safe | linebreaks}}

Be sure of placing the safe tag first, otherwise won't work

A: Late to the party i know, but another option i've been using is using the Wagtail admin, and specifically from wagtail.core.fields import RichTextField. This gives the admin a built-in and very nice Rich Text editor.
You can create basic django models and use the RichTextField as part of the model, and then you can register that model with Wagtail and you get a very nice editing interface with built-in WYSWIG. You can see more here: https://docs.wagtail.io/en/v2.4/reference/contrib/modeladmin/index.html


text:
Q: USB via Thunderbolt Bridge I have a new MacBook Pro (Monterey) networked to a 2014 iMac (High Sierra) via Thunderbolt Bridge. Does anyone know how to access USB devices (e.g. memory stick, disc player) plugged into one computer from the other?

A: I have a 2011 iMac with High Sierra and a 2013 iMac with Catalina connected using a Thunderbolt 1 bridge. I assume the same would be true when using a Thunderbolt 3 bridge even though the hardware is different.
The Network pane of System Preferences on the 2013 iMac shows the following IP address.

From Finder on the 2011 iMac, I can select "Connect to Server...". I then enter the following using the IP address from the previous image.

After connecting, a popup will appear where USB devices (as well as other shared drives and shared folders) on the 2013 iMac can be selected, as shown below. In this case, "Tuna" is an APFS volume on an USB Samsung T7 SSD where Catalina is installed.


text:
Q: onclicklistener for button array is giving null pointer I keep getting a nullpointer exception when I try to implement an onclicklistener for buttons I've created.
    Button setHighBtn[] = null;
    Button setLowBtn[]=null;
    TextView tv[] = new TextView[oNumber];
    for (int i=0;i<oNumber;i++){
        tv[i] = new TextView(this);
        tv[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        tv[i].setText(oName[i]);
        tv[i].setTextSize(20);
        //tv[i].setLayoutParam)
        layout.addView(tv[i]);
        if (capability[i]==0){
            LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            inflater.inflate(R.layout.full_capabilities, layout);
            setHighBtn[i]=(Button)findViewById(R.id.setHigh);
            setHighBtn[i]=(Button)findViewById(R.id.setLow);
            setHighBtn[i].setOnClickListener(this);
            setLowBtn[i].setOnClickListener(this);
        }else{
            setHighBtn[i]=null;
            setLowBtn[i]=null;
        }
    }

A: What did you expect when wrote this?
Button setHighBtn[] = null;
Button setLowBtn[]=null;

A: I think it is a copy-paste error. You wrote:
setHighBtn[i]=(Button)findViewById(R.id.setHigh);
setHighBtn[i]=(Button)findViewById(R.id.setLow); //This is supposed to be setLowBtn[i]

Then you set a listener to setLowBtn which is not initialized yet. Edit it to:
setHighBtn[i]=(Button)findViewById(R.id.setHigh);
setLowBtn[i]=(Button)findViewById(R.id.setLow);


text:
Q: Golang neo4j MERGE requires literal map In my go application, I'm trying to execute a MERGE query, using the golang-neo4j-bolt-driver.
The interface of the ExecNeo and ExecPipeline requires a string map with interface object as a parameter. When executing the query, I get the error message that a literal map is required:

Internal Error(messages.FailureMessage): messages.FailureMessage{Metadata:map[string]interface {}{"code":"Neo.ClientError.Statement.SyntaxError", "message":"Parameter maps cannot be used in MERGE patterns (use a literal map instead`).

Does anyone have an example of creating an literal map?

A: Thanks everyone for pointing me in the right direction.
Here's a piece of sample code that 'works on my machine':
func TestMergeWithLiteralMap(t *testing.T) {
d := bolt.NewDriver()

conn, err := d.OpenNeo("bolt://neo4j:admin@127.0.0.1:7687")
if err != nil {
    panic(err)
}
defer conn.Close()

qry := `MATCH (f:Node1 {Name: {f_name}, Group: {f_group} }),
              (t:Node2{Name: {t_name}, Group: {t_group} })
        WITH f,t
        MERGE (t) <- [:NREL] - (f)`
params := map[string]interface{}{"f_name": "apple", "f_group": "public", "t_name": "pear", "t_group": "private"}
stmt, err := conn.PrepareNeo(qry)
if err != nil {
    panic(err)
}
results, err := stmt.ExecNeo(params)
if err != nil {
    panic(err)
}
glog.Errorf("Executed statement: %s\nWith values: %s\n", stmt, params)

numResult, _ := results.RowsAffected()
metadata := results.Metadata()
glog.Errorf("[NEO-CLIENT] Graphed %s '%s (%s)', CREATED ROWS: %d\n", metadata["kind"], metadata["name"], metadata["namespace"], numResult)

err = stmt.Close()
if err != nil {
    panic(err)
}

}


text:
Q: Google Content Experiements - Add onClick Event With Div? I have an image of a video which is linked, and it is surrounded by Div tag that launches my content locker. I want to track how many times people open the content locker using Google Content Experiments (I have a separate goal setup for actual completion of the locker).
The div class "link_loc" launches my locker successfully, but I'm not sure about the onClick event working correctly with Google Content Experiments.
So this is the code I have... is this correct?

I have searched for a solution but am still very confused (I'm not very technical minded).
Any help appreciated.
Thanks,
Ben


text:
Q: unit testing for portable class library I am building a universal portable library (a dll for universal apps: windows 8.1 & WP 8.1) and I want to add a unit test project to the solution.
I have added a Unit Test Library (windows) project to the solution and the tests are discovered in the test explorer and the unit tests work just fine. But i can't test the dll for Windows Phone.
I have tried a Coded UI Test Project (windows Phone). The test are discovered in test explorer but i can not test async methods. The debugger says
Result StackTrace:

at VeePlayUnitTests.WindowsPhone.CodedUITest1.d__0.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

And if i try the Unit Test App (windows Phone), it does not get discovered by test explorer. I am using VS2013 U4.
What am i missing? How do I run a unit test for WP for a universal portable lib

A: After hours of configuring and playing around with my solution i finally got it working. I don't remember exactly what i did (i remember that the default unit test template is configured wrong). All i can say is that the solution lays in configuring the Configuration Manager correctly for your unit test and the app/lib you are testing. and configure the build properties of the test unit project. What correctly means will depend on what you (and on what device) you are testing. This helped : http://dotnetbyexample.blogspot.ro/2013/06/x86arm-configuration-gotcha-in-windows.html


text:
Q: How to get the key from a TDictionary? I have a TDictionary<TKeyClass, TValueClass>.
I want to accomplish something like
for i := 0 to MyDictionary.Count -1 do
  ShowMessage(MyDictionary.Keys[i].AStringProperty)

I cannot Access the Keys anymore I can just use them if I exactly know them.
Is the only alternative create a TDictionary<TValueClass, TKeyValue> ? So I can loop thorugh the Keys?
The workaroud I found is to create a TList<TKeyClass> but this is something i don't like.

A: Use an enumerator.
for Key in MyDictionary.Keys do
  ShowMessage(Key.AStringProperty);

Since TDictionary is a hash table, you can't access it with integer indexing like an array or TList. But an enumerator works just fine.


text:
Q: Using NSPredicate to filter an NSArray based on NSDictionary keys I have an array of dictionaries.
I want to filter the array based on a key.
I tried this:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SPORT ==  %@)", @"Football"];

NSArray *filteredArray = [data filteredArrayUsingPredicate:predicate];

This doesn't work, I get no results. I think I'm doing something wrong. I know this is the method if "SPORT" was an ivar. I think it is probably different if it is a key.
I haven't been able to find an example however.
Thanks

Update
I added quotes around the string I am searching for.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SPORT ==  '%@')", @"Football"];

It still does not work.

Update 2
Solved it. I actually had to remove the single quotes, which seems to go against what the guide says.
My real problem is I had a nested array and I wasn't actually evaluating the dictionaries. Bone head move.

A: NSPredicate is only available in iPhone 3.0.
You won't notice that until try to run on device.

A: I know it's old news but to add my two cents. By default I use the commands LIKE[cd] rather than just [c]. The [d] compares letters with accent symbols. This works especially well in my Warcraft App where people spell their name "Vòódòó" making it nearly impossible to search for their name in a tableview. The [d] strips their accent symbols during the predicate. So a predicate of @"name LIKE[CD] %@", object.name where object.name == @"voodoo" will return the object containing the name Vòódòó.
From the Apple documentation:
like[cd] means "case- and diacritic-insensitive like.") For a complete description of the string syntax and a list of all the operators available, see Predicate Format String Syntax.

A: It should work - as long as the data variable is actually an array containing a dictionary with the key SPORT
NSArray *data = [NSArray arrayWithObject:[NSMutableDictionary dictionaryWithObject:@"foo" forKey:@"BAR"]];
NSArray *filtered = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(BAR == %@)", @"foo"]];

Filtered in this case contains the dictionary.
(the %@ does not have to be quoted, this is done when NSPredicate creates the object.)

A: #import <Foundation/Foundation.h>
// clang -framework Foundation Siegfried.m
    int
main() {
    NSArray *arr = @[
        @{@"1" : @"Fafner"},
        @{@"1" : @"Fasolt"}
    ];
    NSPredicate *p = [NSPredicate predicateWithFormat:
        @"SELF['1'] CONTAINS 'e'"];
    NSArray *res = [arr filteredArrayUsingPredicate:p];
    NSLog(@"Siegfried %@", res);
    return 0;
}

A: With Swift 3, when you want to filter an array of dictionaries with a predicate based on dictionary keys and values, you may choose one of the following patterns.

#1. Using NSPredicate init(format:arguments:) initializer
If you come from Objective-C, init(format:arguments:) offers a key-value coding style to evaluate your predicate.
Usage:
import Foundation

let array = [["key1": "value1", "key2": "value2"], ["key1": "value3"], ["key3": "value4"]]

let predicate = NSPredicate(format: "key1 == %@", "value1")
//let predicate = NSPredicate(format: "self['key1'] == %@", "value1") // also works
let filteredArray = array.filter(predicate.evaluate)

print(filteredArray) // prints: [["key2": "value2", "key1": "value1"]]

#2. Using NSPredicate init(block:) initializer
As an alternative if you prefer strongly typed APIs over stringly typed APIs, you can use init(block:) initializer.
Usage:
import Foundation

let array = [["key1": "value1", "key2": "value2"], ["key1": "value3"], ["key3": "value4"]]

let dictPredicate = NSPredicate(block: { (obj, _) in
    guard let dict = obj as? [String: String], let value = dict["key1"] else { return false }
    return value == "value1"
})

let filteredArray = array.filter(dictPredicate.evaluate)
print(filteredArray) // prints: [["key2": "value2", "key1": "value1"]]

A: Looking at the NSPredicate reference, it looks like you need to surround your substitution character with quotes. For example, your current predicate reads: (SPORT == Football) You want it to read (SPORT == 'Football'), so your format string needs to be @"(SPORT == '%@')".


text:
Q: I have a Blazor Server app. In my razor page I cannot align my selectbox in a table row , vertically in the middle. What could be the problem? I have tried to use vertical-align:middle both in css and in the select object, but still the select box is aligned to the bottom of the table row.
CSS file
.td_button_bar {
background-color: #eaf2f8;
border: none;
left:10px;
margin-left:10px;
vertical-align:middle;
}

.tr_button_bar {
max-height: 60px;
margin-top: 0px;
top: 0px;
vertical-align: middle;
}

Razor code

     ⓘInfo:  @TagService.Message_CNC_Status

        <button class="button_1" disabled="@TagService.IsDisabled_Read_Drive_Monitor" @onclick="Read_Drive_Monitor">
Start</button>
        <button class="button_1" disabled="@TagService.IsDisabled_Stop_Drive_Monitor" @onclick="Stop_Drive_Monitor">
Stop</button>
        <select style="width:150px; height:30px ;vertical-align:middle;display:inline-block" value="@TagService.Drive_Monitor_selected_AX_No" class="Dep" disabled="@TagService.IsDisabled_Drive_Monitor_selected_AX" @onchange="func_AX_select" @onclick="Read_NC_AX_List_MD10000">
            <option value="-1">--Select AX--</option>
            @for (int j = 0; j < 31; j++)

            {
                var jj = j;
                var kk = j + 1;
                if (Deltalogic.NC_AX_List_MD10000[j] == "")
                {
                    break;
                }
                <option value=@kk>@Deltalogic.NC_AX_List_MD10000[j]</option>
            }

        </select>

A: Try using built-in Bootstrap classes: Grid system and apply align-self-center
Here is a jsFiddle:
https://jsfiddle.net/maciekn/Lx40s7wk/

         ⓘInfo:

                    <button class="button_1" >
Start</button>

                    <button class="button_1" >
Stop</button>

                    <select style="width:150px; height:30px ;vertical-align:middle;display:inline-block">
                    <option value="-1">--Select AX--</option>
                    @for (int j = 0; j < 31; j++)

                    {
                        var jj = j;
                        var kk = j + 1;

                        <option value=@kk></option>
                    }
                    </select>


text:
Q: SharePoint 2013 JavaScript OnClick event On our SharePoint 2013 page we have a button which runs an EXE

I want to generate a JS Alert when the button is clicked so that users know to click RUN

The buttons are being generated by a Content Search Web Part which is reading from a list with a Title and URL field.
For the EXE my url is this: file:///S:/Web/EmailSignature_WPF/EmailSignature_WPF.exe
I tried to embed the JavaScript inline using code such as: javascript:open('file:///S:/Web/EmailSignature_WPF/EmailSignature_WPF.exe') or more basically: JavaScript:alert('TEST');
But SharePoint is giving me an "Invalid URL" message when I try to embed JS in this manner.
I have instead now moved to a Script Editor Web Part and am trying to add the Alert to the OnClick event of my button but this is where I am stuck.
My Script Editor code:
<script style="javascript;">
var img = document.getElementById('ctl00_ctl40_g_a225dbb9_1900_49f2_afe2_ab6f5bf77adf_csr4_pictureOnTop_line1');
img.onclick="javascript:alert('event has been triggered')";</script>

Here is an image of the IE Debug screen which is how I'm pulling the ID.  This H2 element is wrapped in an HREF which is wrapped in two DIV tags which make up an LI

With the above snippet IE Debug is giving me this error message:
Unable to set property 'onclick' of undefined or null reference
I am hoping that this is as simple as misplaced quotations, or assigning the OnClick event to the wrong element, but I'm spinning my wheels. Any help appreciated and I'm happy to clarify

A: You should associate a function to the onclick event on img
<script type="text/javascript">
    var img = document.getElementById('ctl00_ctl40_g_a225dbb9_1900_49f2_afe2_ab6f5bf77adf_csr4_pictureOnTop_line1');
    img.onclick = function () {
    alert('event has been triggered');
};
</script>

A: Say that your page is in the SitePages library and you use jQuery, you can add it to a folder called "js" in the SiteAssets folder, then go back to your Script Editor WP and do it like this:
<script src="../SiteAssets/js/jquery-3.6.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $('input[id*="csr4_pictureOnTop_line1"]').on('click', function() {
        alert('event has been triggered');
    });
</script>


text:
Q: concatenating character and number as one string I wanna make strings like A1, A2...
here is my code:
def random_room(self):
        return chr(random.randint(65, 90)) + chr(random.randint(1, len(self.rooms)))

but it doesn't work

A: There are better abstractions available than using chr to manipulate low-level encodings.
You want to choose a capital letter
import string
from random import choice, randint

letter = choice(string.ascii_uppercase)

and an integer
number = randint(1, len(self.rooms))

then combine them into a single string
room = f'{letter}{number}'

Put it all together:
import string
from random import choice, randint

def random_room(self):
    letter = choice(string.ascii_uppercase)
    number = randint(1, len(self.rooms))
    return f'{letter}{number}'

A: I would have do something like:
def random_room(self):
        return "{}{}".format(chr(random.randint(65, 90)), random.randint(1, len(self.rooms)+1))

so you will have a random letter followed by a number between 1 and len(self.rooms)

A: Use str instead of chr.
return str(random.randint(65, 90)) + str(random.randint(1, len(self.rooms)))

But I think you're trying to do something like this:
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
id = 0 # Your number here
number = letters[id] + str(random.randint(1, ...))


text:
Q: Get contents from radio button array in email I have a sendemail.php set up for sending me information from a form.
The way I have it set to send the information is with
$_POST['variable name']

I cant figure out how to show the choice of a radio button array in the email that is sent to me.  Thanks for any help.

A: Well, all radio buttons in a group necessarily have the same name, to be grouped together. They should each be given a different value. For example, your HTML could look like this:
<input type="radio" name="gender" value="male" id="gender_male" />
    Male
<input type="radio" name="gender" value="female" id="gender_female" />
    Female

Then on your sendemail.php, you look at the value of $_POST['gender'], which will be either "male" or "female", depending which one of the radio buttons they had selected.

A: Every radio button has to have a value set. You get the value of the selected button with $_POST['name of radio button'].


text:
Q: How to launch a windowed shell on a server from a web application I have a web application that should trigger an execution of a batch file on a server at some point. One of the tasks of the batch file is starting a browser on the server machine and doing some on-screen related things - that's why I need it to run in an actual window on the machine and not in a windowless hidden mode.
I tried to use Process class for this, but it only allowed me to run things behind the scenes. Is there a way to launch a command prompt and run a batch file, as if I did it manually, but at the same time monitor when it's done running?


text:
Q: Castle ActiveRecord OneToOne and JoinedBase/Key all together, No SQL Relations Created I'd like to model the following relationship.
[JoinedBase]
MasterForm{
  Guid MasterFormId {get;set;}
 /* some base properties like modifiedBy etc... */
}

[ActiveRecord]
TerminationForm{
   [PrmaryKey(Foreign)]
   Guid MasterFormId {get; set;}
   /* Some more properties specific to terminations */
}

[ActiveRecord("TermStaffing")]
    public class TermStaffing : StaffingBase, ITermStaffing
    {
    }

    public abstract class StaffingBase : EntityBase<StaffingBase>, IStaffingBase
    {
        protected StaffingBase()
        {

        }

        protected StaffingBase(string createdBy)
        {
            this.CreatedBy = createdBy;
        }

        [PrimaryKey(PrimaryKeyType.Foreign)]
        public virtual Guid MasterFormId
        {
            get; set;
        }
}

This all forms the main class inheritance... base form and then some specific forms
..TerminationForm, another form... etc...
And then I was going to hang some other form-sections off each child form.  I modeled those child forms as [OneToOne]
I.e. if TerminationForm is analogous to FormOne above.. I have "Staffing" below it.. this is the link.. and its reciprocal link (Note... I've also pulled up some Staffing properties into an abstract base because I have TerminationStaffing and LeaveStaffing)
[OneToOne(MapType = typeof(TermStaffing), Cascade = CascadeEnum.All, PropertyRef = "MasterFormId", ForeignKey = "FK_TerminationFormsStaffing", Constrained = true)]
        public virtual ITermStaffing Staffing

[OneToOne(MapType = typeof(TerminationForm), PropertyRef = "MasterFormId", ForeignKey = "FK_StaffingTerminationForms", Constrained = true)]
        public virtual ITerminationForm TerminationForm

When AR creates the schema.. it properly relates TerminationForm to MasterForm via the relationship that constrains their Primary Key...
However, even though  TerminationStaffing table includes a MasterFormId I don't see the relation created.  Should I worry about this? Maybe I can just add it after but I was surprised.
I thought about using [BelongsTo] on TerminationStaffing but then what relation goes in TerminationForm (the relation is one to one.. not one to many)
Am I way off base?

A: It turns out that if you use Constrained = true on the "child" side of a OneToOne relationship that this impacts the order in which records are inserted. It also, I believe, may impact the foreign key relationships which AR adds to your Database.
OneToOne has been a great feature for me to do logical separation of a big datamodel into tables which have less responsibility.


text:
Q: Convert an object datatype column with format mm:ss to a time format pandas I have a dataframe that has an column that has an object datatype with the format mm:ss.  I want to convert that column to a time format so that I could turn the time into seconds instead of mm:ss.  However, I have not been able to convert the column into a time format.
Example of my data:
time
33:22
24:56
30:15
26:57

I have tried:
df['time'] = pd.to_timedelta(df['time'])

How do I convert this object data type column to a time format?  And ultimately to total seconds?

A: Just add '00:' to the beginning.
df['time'] = pd.to_timedelta('00:' + df['time'])
df['total seconds'] = df['time'].dt.total_seconds()


text:
Q: Erro em código PHP de "Invalid parameter number" em código de venda que deve repor ou retirar a quantidade de produtos em outra tabela Meu código envolve a atualização de uma venda PHP deve realizar duas ações quando atualizados:

*

*Fazer o cálculo total da venda na tabela itens_venda(caso a coluna quantidade seja alterada deva fazer um novo cálculo. STATUS: Executa)

*Repor a quantidade ou retirar da tabela produto (STATUS: Não executa).

Vou explicar com um exemplo:

*

*Existem uma quantidade de 15 produtos de um registro da tabela produto.

*

*E foram vendidos uma quantidade de 5 produtos na tabela itens_venda.

*

*Caso a quantidade de 5 fosse alterada para um valor menor para 2 os 3 produtos voltariam para
o registro da tabela produto, ficando com o total de 18 produtos ao invés de 15.

*

*E a tabela itens_venda registraria 2 produtos vendidos ao invés de 5.

*

*Caso a quantidade de 5 fosse alterada para um valor maior para 7 haveria uma retirada de mais 2 produtos do registro da tabela produto, ficando com o total de 13 produtos ao invés de 15.

*

*E a tabela itens_venda registraria 7 produtos vendidos ao invés de 5.

Só que o seguinte erro acontecesse:
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
Linha do erro: $quantidade_produto->execute();

*

*Formulário de atualização da venda

<form method="POST">
    <p> ID item venda:
    <select name="cd_itens_venda" required="">
            <option value=""> </option>
            <?php
                foreach ($resultado_vendas as $valor) {
                    echo "<option value='{$valor['cd_itens_venda']}'>{$valor['cd_itens_venda']}</option>";
                }
            ?>
        </select>
        </p>

        <p> ID produto:
            <select name="cd_produto" required="">
                <option value=""> </option>
                <?php
                    foreach ($resultado_produto as $v1) {
                        echo "<option value='{$v1['cd_produto']}'>{$v1['nome']}</option>";
                    }
                ?>
            </select>
        </p>

        <p> ID funcionário:
            <select name="cd_funcionario" required="">
                <option value=""> </option>
                <?php
                    foreach ($resultado_funcionario as $v2) {
                        echo "<option value='{$v2['cd_funcionario']}'>{$v2['nome']}</option>";
                    }
                ?>
            </select>
        </p>

        <p> ID cliente:
            <select name="cd_cliente" required="">
                <option value=""> </option>
                <?php
                    foreach ($resultado_cliente as $v3) {
                        echo "<option value='{$v3['cd_cliente']}'>{$v3['nome']}</option>";
                    }
                ?>
            </select>
        </p>
        <p> Pagamento:
            <select name="tipo_pagamento" required="">
                <option value=""> </option>
                <option value="Pagamento á vista">Pagamento á vista</option>
            </select>
        </p>
        <p> Valor do item: <input type="text" name="valor_item" step="0.01" required=""> </p>
        <p> Quantidade: <input type="number" name="quantidade" size="30" required=""> </p>
        <button name="Atualizar"> Atualizar item de venda </button>
</form>

*

*Código PHP completo

<?php
    require_once 'conexao.php';

    if(isset($_POST['Atualizar'])){
        // Especifica a variável
        $cd_itens_venda = $_POST['cd_itens_venda'];
        $cd_produto = $_POST['cd_produto'];
        $cd_funcionario = $_POST['cd_funcionario'];
        $cd_cliente = $_POST['cd_cliente'];
        $tipo_pagamento = $_POST['tipo_pagamento'];
        $valor_item = $_POST['valor_item'];
        $quantidade = $_POST['quantidade'];
        // Cálcula o valor total da compra multiplicando o valor com a quantidade
        $valor_total = ($valor_item * $quantidade);
        try {
            // Tabela ITENS_VENDA
            $conexao->beginTransaction();
            $atualizacao = "UPDATE itens_venda SET cd_produto = :cd_produto,
            cd_funcionario = :cd_funcionario, cd_cliente = :cd_cliente,
            tipo_pagamento = :tipo_pagamento, valor_item = :valor_item,
            quantidade = :quantidade, valor_total = :valor_total WHERE cd_itens_venda = :cd_itens_venda";
            $atualiza_dados = $conexao->prepare($atualizacao);
            $atualiza_dados->bindValue(':cd_itens_venda',$cd_itens_venda);
            $atualiza_dados->bindValue(':cd_produto',$cd_produto);
            $atualiza_dados->bindValue(':cd_funcionario',$cd_funcionario);
            $atualiza_dados->bindValue(':cd_cliente',$cd_cliente);
            $atualiza_dados->bindValue(':tipo_pagamento',$tipo_pagamento);
            $atualiza_dados->bindValue(':valor_item',$valor_item);
            $atualiza_dados->bindValue(':quantidade',$quantidade);
            $atualiza_dados->bindValue(':valor_total',$valor_total);
            $atualiza_dados->execute();

            // Tabel PRODUTO
            // Query que faz o cálculo da diferença do produto atualizado
            $nova_quantidade = "UPDATE itens_venda SET quantidade = quantidade - :quantidade
            WHERE cd_itens_venda = :cd_itens_venda";
            // Query que faz a busca do registro do produto para fazer a reposição
            $procurar_produto = "SELECT quantidade FROM produto WHERE cd_produto = :cd_produto";
            // Condicional para saber se vai tirar ou adicionar mais produtos
            if ($nova_quantidade < $quantidade) {
                // Haverá retirada de produto (caso a nova quantidade seja menor que a antiga)
                $calculo_reposicao = "UPDATE produto SET quantidade = '$procurar_produto' - quantidade WHERE cd_produto = :cd_produto";
            }else{
                // Haverá reposição do produto (caso a nova quantidade seja maior que a antiga)
                $calculo_reposicao = "UPDATE produto SET quantidade = '$procurar_produto' + quantidade WHERE cd_produto = :cd_produto";
            }
            $quantidade_produto = $conexao->prepare($calculo_reposicao);
            $quantidade_produto->bindValue(':cd_itens_venda',$cd_itens_venda);
            $quantidade_produto->bindValue(':cd_produto',$cd_produto);
            $quantidade_produto->bindValue(':quantidade',$quantidade);
            $quantidade_produto->execute(); // Linha do erro
            $conexao->commit();

        } catch (PDOException $falha_atualizacao) {
            echo "A atualização não foi feita".$falha_atualizacao->getMessage();
        }
    }
    // Query que seleciona chave de itens_venda
    $seleciona_vendas = $conexao->query("SELECT cd_itens_venda FROM itens_venda");
    // Resulta em uma matriz
    $resultado_vendas = $seleciona_vendas->fetchAll();

    // Query que seleciona chave e nome do produto
    $seleciona_produto = $conexao->query("SELECT cd_produto, nome FROM produto");
    // Resulta em uma matriz
    $resultado_produto = $seleciona_produto->fetchAll();

    // Query que seleciona chave e nome do funcionario
    $seleciona_funcionario = $conexao->query("SELECT cd_funcionario, nome FROM funcionario");
    // Resulta em uma matriz
    $resultado_funcionario = $seleciona_funcionario->fetchAll();

    // Query que seleciona chave e nome do cliente
    $seleciona_cliente = $conexao->query("SELECT cd_cliente, nome FROM cliente");
    // Resulta em uma matriz
    $resultado_cliente = $seleciona_cliente->fetchAll();
?>

A: Invalid parameter number - o erro significa que há uma quantidade de parâmetros inválidos entre os Binds e a SQL
As variáveis $procurar_produto e $nova_quantidade devem retornar algo similar a:
$procurar_produto: SELECT quantidade FROM produto WHERE cd_produto = :cd_produto
$nova_quantidade: UPDATE itens_venda SET quantidade = quantidade - :quantidade WHERE cd_itens_venda = :cd_itens_venda
o que não é o desejado

Comparando $nova_quantidade < $quantidade vai cair sempre no else da condicional

"UPDATE produto SET quantidade = '$procurar_produto' + quantidade WHERE cd_produto = :cd_produto";

e substituindo

$procurar_produto por SELECT quantidade FROM produto WHERE cd_produto = :cd_produto

deve gerar uma query assim

UPDATE produto SET quantidade = 'SELECT quantidade FROM produto WHERE cd_produto = :cd_produto' + quantidade WHERE cd_produto = :cd_produto

a qual não vai executar absolutamente nada.

Diante de tais problemas fiz as devidas correções e acredito que vá funcionar a contento e isso você que vai me dizer.
O código está comentado
<?php

   require_once 'conexao.php';

    if(isset($_POST['Atualizar'])){
        // Especifica a variável
        $cd_itens_venda = $_POST['cd_itens_venda'];
        $cd_produto = $_POST['cd_produto'];
        $cd_funcionario = $_POST['cd_funcionario'];
        $cd_cliente = $_POST['cd_cliente'];
        $tipo_pagamento = $_POST['tipo_pagamento'];
        $valor_item = $_POST['valor_item'];
        $quantidade = $_POST['quantidade'];
        // Cálcula o valor total da compra multiplicando o valor com a quantidade
        $valor_total = ($valor_item * $quantidade);

        try {

            // Quantidade inicial na tabela itens_venda
            $procurar_produto = "SELECT quantidade FROM itens_venda WHERE cd_produto = :cd_produto";
            $busca_registro = $conexao->prepare($procurar_produto);
            $busca_registro->bindValue(':cd_produto',$cd_produto);
            $busca_registro->execute();
            $linha = $busca_registro->fetch(PDO::FETCH_ASSOC);
            $quantidade_antiga = $linha['quantidade'];

            // Tabela ITENS_VENDA
            $conexao->beginTransaction();
            $atualizacao = "UPDATE itens_venda SET cd_produto = :cd_produto,
            cd_funcionario = :cd_funcionario, cd_cliente = :cd_cliente,
            tipo_pagamento = :tipo_pagamento, valor_item = :valor_item,
            quantidade = :quantidade, valor_total = :valor_total WHERE cd_itens_venda = :cd_itens_venda";
            $atualiza_dados = $conexao->prepare($atualizacao);
            $atualiza_dados->bindValue(':cd_itens_venda',$cd_itens_venda);
            $atualiza_dados->bindValue(':cd_produto',$cd_produto);
            $atualiza_dados->bindValue(':cd_funcionario',$cd_funcionario);
            $atualiza_dados->bindValue(':cd_cliente',$cd_cliente);
            $atualiza_dados->bindValue(':tipo_pagamento',$tipo_pagamento);
            $atualiza_dados->bindValue(':valor_item',$valor_item);
            $atualiza_dados->bindValue(':quantidade',$quantidade);
            $atualiza_dados->bindValue(':valor_total',$valor_total);
            $atualiza_dados->execute();

            // Tabel PRODUTO
            // Query que faz o cálculo da diferença do produto atualizado

            /* #########  serve pra nada pode excluir #######################################
            $nova_quantidade = "UPDATE itens_venda SET quantidade = quantidade - :quantidade
            WHERE cd_itens_venda = :cd_itens_venda";
            ############################################################################### */

            // Condicional para saber se vai tirar ou adicionar mais produtos
            // fiz algumas correções nessa lógica e acho que dá para entender

            if ($quantidade < $quantidade_antiga) {
                // Haverá reposição do produto (caso a nova quantidade seja menor que a antiga)
                $calculo_reposicao = "UPDATE produto SET quantidade = quantidade + ('$quantidade_antiga'-:quantidade) WHERE cd_produto = :cd_produto";
            }else{
                // Haverá retirada de produto (caso a nova quantidade seja maior que a antiga)
                $calculo_reposicao = "UPDATE produto SET quantidade = quantidade - (:quantidade-'$quantidade_antiga') WHERE cd_produto = :cd_produto";
            }

            $quantidade_produto = $conexao->prepare($calculo_reposicao);

    /* linha indevida ################################################ */
    //$quantidade_produto->bindValue(':cd_itens_venda',$cd_itens_venda);
    /* ############################################################### */

            $quantidade_produto->bindValue(':cd_produto',$cd_produto);
            $quantidade_produto->bindValue(':quantidade',$quantidade);
            $quantidade_produto->execute();
            $conexao->commit();

        } catch (PDOException $falha_atualizacao) {
            echo "A atualização não foi feita".$falha_atualizacao->getMessage();
        }
    }
    // Query que seleciona chave de itens_venda
    $seleciona_vendas = $conexao->query("SELECT cd_itens_venda FROM itens_venda");
    // Resulta em uma matriz
    $resultado_vendas = $seleciona_vendas->fetchAll();

    // Query que seleciona chave e nome do produto
    $seleciona_produto = $conexao->query("SELECT cd_produto, nome FROM produto");
    // Resulta em uma matriz
    $resultado_produto = $seleciona_produto->fetchAll();

    // Query que seleciona chave e nome do funcionario
    $seleciona_funcionario = $conexao->query("SELECT cd_funcionario, nome FROM funcionario");
    // Resulta em uma matriz
    $resultado_funcionario = $seleciona_funcionario->fetchAll();

    // Query que seleciona chave e nome do cliente
    $seleciona_cliente = $conexao->query("SELECT cd_cliente, nome FROM cliente");
    // Resulta em uma matriz
    $resultado_cliente = $seleciona_cliente->fetchAll();

?>

No caso de delete é como segue
<?php
require_once 'conexao.php';
    if(isset($_POST['Deletar'])){
    // Especifica a variável
    $cd_itens_venda = $_POST['cd_itens_venda'];
    try {
            $conexao->beginTransaction();
            // Quantidade inicial na tabela itens_venda
            $procurar_produto = "SELECT cd_produto,quantidade FROM itens_venda WHERE cd_itens_venda = :cd_itens_venda";
            $busca_registro = $conexao->prepare($procurar_produto);
            $busca_registro->bindValue(':cd_itens_venda',$cd_itens_venda);
            $busca_registro->execute();
            $linha = $busca_registro->fetch(PDO::FETCH_ASSOC);

            //variaveis a serem usadas no update da tabela produto

            $quantidade = $linha['quantidade'];
            $cd_produto = $linha['cd_produto'];

        // TABELA ITENS_VENDA
        $remove = "DELETE FROM itens_venda WHERE cd_itens_venda = :cd_itens_venda";
        $remocao = $conexao->prepare($remove);
        $remocao->bindValue(':cd_itens_venda',$cd_itens_venda);
        $remocao->execute();

        // Query que faz a atualização da quantidade de estoque da tabela produto
        $atualiza_quantidade = "UPDATE produto SET quantidade = quantidade + ('$quantidade') WHERE cd_produto = '$cd_produto'";
        $quantidade_produto = $conexao->prepare($atualiza_quantidade);
        $quantidade_produto->execute();

        $conexao->commit();
    } catch (PDOException $falha_remocao) {
        echo "A remoção não foi feita".$falha_remocao->getMessage();
    }
}
// Query que seleciona o registro de itens_venda
$seleciona_nomes = $conexao->query("SELECT cd_itens_venda FROM itens_venda");
// Resulta em uma matriz
$resultado_selecao = $seleciona_nomes->fetchAll();
?>

A: Olá, Tudo bem?
Pelo que notei, o erro acontece porque você está dando bind em tokens que não existem.
Note que a sua variável da query está assim:
$calculo_reposicao = "UPDATE produto SET quantidade = '$procurar_produto' - quantidade WHERE cd_produto = :cd_produto";

O único token dela é :cd_produto.
Porem no objeto você está colocando
$quantidade_produto->bindValue(':cd_produto',$cd_produto);
$quantidade_produto->bindValue(':quantidade',$quantidade);

O seu erro está vindo dessa variável quantidade, que não existe na query. tente tirar esta variável e vê se funciona.
Abs

A: Fala amigo, tudo certo? Você não está passando :cd_itens_venda e :quantidade na query $calculo_reposicao mas está dando bind nelas.
Tem quantidade mas está sem os : na query para referenciar:
[..]SET quantidade = '$procurar_produto' - /*faltam os dois pontos (:) aqui */quantidade WHERE cd_produto[...]

Basta remover essas linhas:
$quantidade_produto->bindValue(':cd_itens_venda',$cd_itens_venda);
$quantidade_produto->bindValue(':quantidade',$quantidade); //Remova esta linha se não for usar o :quantidade na query $calculo_reposicao.

Obs: Não sei se passou resumido o código mas está faltando executar as duas queries das variáveis para obter o total: $nova_quantidade e $procurar_produto
Abraços!

A: @vorbbel,
Me parece que existe um erro em sua pergunta, se vc tem 15 e foram vendidos uma quantidade de 5 itens e depois 3 foram retirados, sendo vendidos apenas 2, então o seu estoque ficaria com 13 e não 18 como vc informa na sua pergunta.
Sobre o erro, o log informa um erro sql onde o número de parâmetros que vc está passando no execute não é igual ao numero de colunas da sua tabela... verifique seu sql $calculo_reposicao. Faça um teste dessa consulta direto no seu banco de dados e veja se está correta, se estiver, então vc verifica se tem algum erro no seu código em relação aos parâmetros/colunas e compara com o resultado que vc obteve direto no banco...


text:
Q: Autofac Func with InstancePerMatchingLifetimeScope When evaluating Func<T> where T is registered with InstancePerMatchingLifetimeScope, inside a singleton class, shouldn't it provide the same instance? that is, shouldn't Func<T> be "scope-aware"?
Maybe an example would be better.
I have two class:
    class MyScoped
    {
        public int Num { get; set; }
    }

    class MySingleton
    {
        readonly Func<MyScoped> scoped;

        public MySingleton(Func<MyScoped> scoped)
        {
            this.scoped = scoped;
        }

        public void Do()
        {
            var scopedObj = scoped();

            Console.WriteLine(scopedObj.Num);
        }
    }

Which are registered like this:
        var builder = new ContainerBuilder();

        builder.RegisterType<MyScoped>().InstancePerMatchingLifetimeScope("MyScope", "root");
        builder.RegisterType<MySingleton>().SingleInstance();

        var container = builder.Build();

And I am running the following piece of code:
        var singleton = container.Resolve<MySingleton>();

        singleton.Do();

        using (var scope = container.BeginLifetimeScope("MyScope"))
        {
            var scoped = scope.Resolve<MyScoped>();

            scoped.Num = 1;

            singleton.Do();
        }

I would expect that the first call to Do() would print 0, and the second would print 1.
I had to changed MySingleton to InstancePerDependency so it would work, which is a bad solution for me, because MySingleton can be expensive to create.
What am I missing here?

A: It seems services registered as single instance are resolved in the context of root scope. It means that your Func<MyScoped> injected to MySingleton would always resolve MyScoped from the root. The following code:
var singleton = container.Resolve<MySingleton>();
var s = container.Resolve<MyScoped>();

s.Num = 1;

singleton.Do();

using (var scope = container.BeginLifetimeScope("MyScope"))
{
    var scoped = scope.Resolve<MyScoped>();

    scoped.Num = 10;

    singleton.Do();
}

would print 1 twice, because var scopedObj = scoped(); in Do() method would resolve MyScoped from root container, not from the scope.
You could achieve what you want by passing required dependency manually into Do() method:
class MySingleton
{
    public void Do(MyScoped myScoped)
    {
        Console.WriteLine(myScoped.Num);
    }
}

// ...

var singleton = container.Resolve<MySingleton>();
var s = container.Resolve<MyScoped>();

s.Num = 1;

singleton.Do(s);

using (var scope = container.BeginLifetimeScope("MyScope"))
{
    var scoped = scope.Resolve<MyScoped>();

    scoped.Num = 10;

    singleton.Do(scoped);
}

It would print 1 and 10 respectively.


text:
Q: Probability of real roots(short way) Each coefficient in the equation $ax^2+bx+c$ is determined by throwing an ordinary dice. Find the probability that the given equation will have real roots?
I counted the cases which fulfill D(discriminant) greater than zero, but that turned into a long method.
Is there an elegant short way to do this question?


text:
Q: Flutter - Screen dont render when state change I have this ListView widget:
class OperationsView extends StatelessWidget {
  OperationsView({Key? key}): super(key: key);

  @override
  Widget build(BuildContext context){
    return BlocBuilder<MonitorBloc, MonitorState>(
      builder: (context, state) => getOperationListView(state.operationsCollection),
    );
  }

  ListView getOperationListView(OperationsCollection operationsCollection){
    return ListView.builder(
      padding: const EdgeInsets.all(10),
      itemCount: operationsCollection.length(),
      itemBuilder: (context, position) => OperationContainer(
          amount: operationsCollection.getOperationAtIndex(position).amount,
          description: operationsCollection.getOperationAtIndex(position).description,
          isEntry: operationsCollection.getOperationAtIndex(position).isEntry,
          date: operationsCollection.getOperationAtIndex(position).date),
    );
  }
}

When i insert a new operation, the screen dont re-render, i need close the app and open again to see new operations inserted.
This is how i save the new operation:
 ElevatedButton(onPressed: () {
                  if (_formKey.currentState!.validate()) {
                    _formKey.currentState!.save();
                    BlocProvider.of<ManageBloc>(context).add(SubmitEvent(operation: operation));

                    _formKey.currentState!.reset();
                  }
                }, child: const Text("Salvar"))

And my Blocs:
class MonitorBloc extends Bloc<MonitorEvent, MonitorState> {
  OperationsCollection operationsCollection = OperationsCollection();

  MonitorBloc() : super(MonitorState(operationsCollection: OperationsCollection())) {
    LocalDatabase.helper.stream.listen((event) {
      String noteId = event[0];

      if (event[1] == null) {
        operationsCollection.deleteOperationOfId(noteId);
      } else {
        operationsCollection.updateOperationOfId(noteId, event[1]);
      }
      add(UpdateList());
    });

    on<AskNewList>((event, emit) async {
      operationsCollection = await LocalDatabase.helper.getOperationList();
      emit(MonitorState(operationsCollection: operationsCollection));
    });

    on<UpdateList>((event, emit) {
      emit(MonitorState(operationsCollection: operationsCollection));
    });
    add(AskNewList());
  }
}

class ManageBloc extends Bloc<ManageEvent, ManageState> {
  ManageBloc(): super(InsertState()) {
    on<UpdateRequest>((event, emit) {
      emit(UpdateState(operationId: event.operationId, previousOperation: event.previousOperation));
    });

    on<UpdateCancel>((event, emit) {
      emit(InsertState());
    });

    on<SubmitEvent>((event, emit) {
      if (state is InsertState) {
        LocalDatabase.helper.insertOperation(event.operation);
      }
      emit(InsertState());
    });
    on<DeleteEvent>((event, emit) {
    });
  }
}

What could be happing?
The bloc is saving the operation in local storage, but dont render the screen when i change the state value.


text:
Q: Why is special character coming out strange from MySql db after I changed to sessions? I have a classified website, and I recently changed the insertion of classifieds to use php Session variables instead of alot of POST and FORMS...
So first BEFORE changing to Sessions, it worked nice and all special characters showed up correctly.
Now that I changed to SESSIONS, I get funny characters instead of the special characters.
Here is some code to explain better.
First is BEFORE changing to sessions:
Below is the first page which shows a verification page (preview), where users may press "OK" or "Go back and change":
  //VERIFICATION PAGE:
  <form>
   <input type="text" value="<?php echo htmlentities($_POST['annonsera_headline'], ENT_QUOTES, 'utf-8'); ?>">

  //IF OK, THEN TO THE PAGE WHERE THE CLASSIFIED IS INSERTED
   $headline= mysql_real_escape_string($_POST['headline']);

Now the above worked but then I changed to sessions:
    //VERIFICATION PAGE:
    $headline = htmlentities($_POST['annonsera_headline'], ENT_QUOTES, 'utf-8');
    $_SESSION['headline'] = $headline;

  //IF OK, THEN TO THE PAGE WHERE THE CLASSIFIED IS INSERTED
  $headline= mysql_real_escape_string($_SESSION['headline']);

The above here changed all characters in the headline to corresponding HTML ENTITIES.
What should I do here?
And in my MySql headline field, there is no HTML ENTITY, there is the correct text. But on my webpages and in the classified the special characters show up funny, even though they are taken from the same mysql field (which looks good in phpmyadmin).
Any ideas?
Thanks

A: Ensure that your connection to mysql is utf8 safe first of all I would start by issuing a SET NAMES UTF8 to the database just after you connect.  Also ensure that your table field is also utf-8 by setting the tables collation
Hope that helps

A: You're HTML-encoding your submitted headline before putting it into the session. Then you get the encoded value out of the session and insert it into the database.
Neither the session store nor the database is HTML, so you shouldn't be encoding the values here. You should only HTML-encode text when you're outputting it to an HTML page (like the <input> in the first example). Also, you should probably use htmlspecialchars() in preference to htmlentities(), which pointlessly tries to use HTML entity references for some (but not all) Unicode characters.
Ensure that your page is served as UTF-8 (with a Content-Type header and/or <meta>), your database connection is set to use UTF-8 (using mysql_set_charset(), preferably not SET NAMES) and that each text column of each table is set to use a UTF-8 collation.
For what it's worth I would not use sessions here. For doing multi-stage forms, using hidden values to pass previous inputs is more reliable: consider what happens when the user opens two browser windows and tries to enter two classifieds simultaneously. The values from one form will overwrite the values from the other form, mixing up the two processes. (The other alternative is to have a single-page form with some client-side scripting to show only part of it at once.)


text:
Q: let variable is undefined in useImperativeHandle function I work with the lottie-web package in a .web.js file under React Native (Expo).
My problem is that the let variable anim is undefined in the functions in useImperativeHandle. In the useEffect anim works wonderfully. For example if I access anim.play() right after the initialize at useEffect it works. But at the play() function in imperative it doesn't work.
At my parent component I create a ref with useRef and pass the ref to the component
const lottieAnim = useRef(null);

--
let anim;
useEffect(() => {
  const lottieOptions = {
    container: divContainer.current,
    renderer: 'svg',
    loop,
    autoplay,
    segments: segments !== false,
    animationData,
    rendererSettings,
  };
  anim = lottie.loadAnimation({ ...lottieOptions, ...options });
  // anim.play(); works here

  if (onAnimationFinish) {
    anim.addEventListener('complete', onAnimationFinish);
  }
}, []);

useImperativeHandle(ref, () => ({
  stop() {
    anim.stop();
  },
  pause() {
    anim.pause();
  },
  play() {
    anim.play();
    // anim is undefined
  },
  setSpeed(s) {
    anim.setSpeed(s);
  },
  setDirection(d) {
    anim.setDirection(d);
  },
  playSegments(s) {
    anim.playSegments(s);
  },
}));

A: Update 2023
I've created a package for connecting third-party packages to react via useImperativeHandler in an easier way, you might find it useful and easier to use .
react-aptor
That is because React has no clue what anim is when it creates API functions in useImperativeHandle (duo to closure and react updating strategies that don't trigger any update by mutating a variable). There is some way you can handle this, after all, it comes to personal opinion what to do, I will use something like this which work the best
for me.
Add GetApi Function
// hanlder.js
const stop = anim => anim.stop()
// api.js
const getAPI = anim => () => ({
  stop: stop.bind(this, anim),
  // or simply
  setSpeed: s => anim.setSpeed(s),

  // you can mock APIs here if anim is null or throw an Error
});

store anim in a state

store anim in the state for the first render only and use it in the dependencies array of getApi useEffect

const [anim, setAnim] = React.useState(null);

React.useEffect(() => {
  // initialization part
}, []);

React.useImperativeHandle(ref, getAPI(anim), [anim]);


text:
Q: Performing a multi-finger swipe using XCUITest I am working with an app that supports swipe gestures with multi-fingers (2 finger down swipe, etc.), and would like to simulate this in XCUITests. I see that XCUIElement contains a bunch of functions like SwipeUp() and SwipeLeft(), however they all see to be for only single fingers. I don't see any other APIs that look like they would allow simulating a two-finger down swipe, for instance.
Does anyone know of a way to do this?

A: Unfortunately, there isn't a solution for this until we're given a specific call for it; the existing gestures are all synchronous so you can't simulate individual fingers doing different things at the same time.
There are pinch and rotate functions, but they can't be made to do what you're looking for.


text:
Q: radio button group for nested form in rails How to create radio button in rails 3 when using nested form up to third level.
I have a group of radio buttons for listing . How can we achieve radio button with group name, attribute, value
f.fields_for :items do |item|
    item.fields_for :item_lists do |list|
        list.radio_button "radio_option_#{list.object.item_id}", :gender, 1
    end
end
end

But this is not working as i had radio buttons based on Group name.
thanks in advance.

A: Use form_for and fields_for:
= form_for @group do |f|
 - @group.users.each do |user|
  = f.fields_for user |u|
   = u.radio_button :gender

You can read more about usage here. I used HAML for the notation.


text:
Q: How do I use Head and Tail to print specific lines of a file I want to say output lines 5 - 10 of a file, as arguments passed in.
How could I use head and tail to do this?
where firstline = $2 and lastline = $3 and filename = $1.
Running it should look like this:
./lines.sh filename firstline lastline

A: try this one-liner:
awk -vs="$begin" -ve="$end" 'NR>=s&&NR<=e' "$f"

in above line:
$begin is your $2
$end is your $3
$f is your $1

A: Save this as "script.sh":
#!/bin/sh

filename="$1"
firstline=$2
lastline=$3
linestoprint=$(($lastline-$firstline+1))

tail -n +$firstline "$filename" | head -n $linestoprint

There is NO ERROR HANDLING (for simplicity) so you have to call your script as following:
./script.sh yourfile.txt firstline lastline
$ ./script.sh yourfile.txt 5 10

If you need only line "10" from yourfile.txt:
$ ./script.sh yourfile.txt 10 10

Please make sure that:
(firstline > 0) AND (lastline  > 0) AND (firstline <= lastline)

A: head -n XX # <-- print first XX lines
tail -n YY # <-- print last YY lines

If you want lines from 20 to 30 that means you want 11 lines starting from 20 and finishing at 30:
head -n 30 file | tail -n 11
#
# first 30 lines
#                 last 11 lines from those previous 30

That is, you firstly get first 30 lines and then you select the last 11 (that is, 30-20+1).
So in your code it would be:
head -n $3 $1 | tail -n $(( $3-$2 + 1 ))

Based on firstline = $2, lastline = $3, filename = $1
head -n $lastline $filename | tail -n $(( $lastline -$firstline + 1 ))

A: Aside from the answers given by fedorqui and Kent, you can also use a single sed command:
#!/bin/sh
filename=$1
firstline=$2
lastline=$3

# Basics of sed:
#   1. sed commands have a matching part and a command part.
#   2. The matching part matches lines, generally by number or regular expression.
#   3. The command part executes a command on that line, possibly changing its text.
#
# By default, sed will print everything in its buffer to standard output.
# The -n option turns this off, so it only prints what you tell it to.
#
# The -e option gives sed a command or set of commands (separated by semicolons).
# Below, we use two commands:
#
# ${firstline},${lastline}p
#   This matches lines firstline to lastline, inclusive
#   The command 'p' tells sed to print the line to standard output
#
# ${lastline}q
#   This matches line ${lastline}.  It tells sed to quit.  This command
#   is run after the print command, so sed quits after printing the last line.
#
sed -ne "${firstline},${lastline}p;${lastline}q" < ${filename}

Or, to avoid any external utilites, if you're using a recent version of bash (or zsh):
#!/bin/sh

filename=$1
firstline=$2
lastline=$3

i=0
exec <${filename}  # redirect file into our stdin
while read ; do    # read each line into REPLY variable
  i=$(( $i + 1 ))  # maintain line count

  if [ "$i" -ge "${firstline}" ] ; then
    if [ "$i" -gt "${lastline}" ] ; then
      break
    else
      echo "${REPLY}"
    fi
  fi
done


text:
Q: Better way to obtain a smaller vertical line | scaled to math? I am trying to write the following line as can be seen below
\documentclass[border=1mm]{standalone}
\usepackage{graphicx}
\begin{document}
\Huge $\cup \ \cap \ \raisebox{0.30 ex}{\scalebox{1}[0.62]{$\mid$}}$
\end{document}

Which results in

Is there an easier or better way to make sure the vertical line \mid
is scaled correctly to \cup and \cap? In particular

*

*They should have the same baseline, height and width.

My solution feels very hackish and not quite right.

A: \stretchrel from the scalerel package allows you to do such things.
\documentclass[border=1mm]{standalone}
\usepackage{scalerel}
\begin{document}
\Huge $\cup \ \cap \ \stretchrel*{\mid}{\cap}$
\end{document}

A: For Computer Modern, use pict2e:
\documentclass{article}
\usepackage{pict2e}
\usepackage{color} % for the comparison

\makeatletter
\newcommand{\cbar}{\mathbin{\mathpalette\c@bar\relax}}
\newcommand{\c@bar}[2]{%
  \begingroup
  \sbox\z@{$#1\cup$}%
  \setlength{\unitlength}{\dimexpr\ht\z@+\dp\z@}%
  \mkern1mu
  \raisebox{-\dp\z@}{%
    \begin{picture}(0,1)
    \roundcap
    \c@bar@thickness{#1}%
    \Line(0,0)(0,1.03)
    \end{picture}%
  }%
  \mkern1mu
  \endgroup
}
\newcommand{\c@bar@thickness}[1]{%
  \linethickness{%
    \ifx#1\displaystyle 1\fontdimen8\textfont\else
    \ifx#1\textstyle 1\fontdimen8\textfont\else
    \ifx#1\scriptstyle 0.85\fontdimen8\scriptfont\else
    0.75\fontdimen8\scriptscriptfont\fi\fi\fi 3
  }%
}
\makeatother

\begin{document}

${\cup}{\cap}{\cbar}$

$\scriptstyle{\cup}{\cap}{\cbar}$

$\scriptscriptstyle{\cup}{\cap}{\cbar}$

${\cup}\mkern-2.3mu{\textcolor{red}{\cbar}}{\textcolor{red}{\cup}}\mkern-2.3mu{\cbar}$
${\cap}\mkern-2.3mu{\textcolor{red}{\cbar}}{\textcolor{red}{\cap}}\mkern-2.3mu{\cbar}$

$\scriptstyle{\cup}\mkern-2.4mu{\textcolor{red}{\cbar}}{\textcolor{red}{\cup}}\mkern-2.4mu{\cbar}$
$\scriptstyle{\cap}\mkern-2.4mu{\textcolor{red}{\cbar}}{\textcolor{red}{\cap}}\mkern-2.4mu{\cbar}$

$\scriptscriptstyle{\cup}\mkern-2.8mu{\textcolor{red}{\cbar}}{\textcolor{red}{\cup}}\mkern-2.8mu{\cbar}$
$\scriptscriptstyle{\cap}\mkern-2.8mu{\textcolor{red}{\cbar}}{\textcolor{red}{\cap}}\mkern-2.8mu{\cbar}$

\end{document}


text:
Q: XLSX file created on linux has different name when sending it to windows I can't specify in which moment something goes wrong.
On linux via script im creating xlsx file using xlsxwriter. The thing is on linux created files have correct name, then when i open them on windows (thanks to network location) they have totally different names.
The code:
#!/usr/bin/env python
# *-* coding: utf-8 *-*

import xlsxwriter
from datetime import datetime

if __name__ == "__main__":
    pass

class Excel:
    def __init__(self):
        now = datetime.now()
        datetoday = now.strftime("%d.%m.%Y-%H:%M:%S")
        workbook = xlsxwriter.Workbook('GMDC_' + datetoday + '.xlsx')
        workbook.close()

Example created file by this
GMDC_03.09.2019-16:41:00.xlsx
GMDC_05.09.2019-08:42:03.xlsx
The same files but visible on windows
GMDC_0~1
GMDC_0~2
Is there something wrong with encoding or the datetime format which could be the issue?


text:
Q: Do I have to use NavigationController in my coordinators code? I am refactoring my codes and want to give Coordinators a try.
However, I am not quite comfortable with UINavigationController in charge, cause it creates a Back button on child coordinates as well as an unwanted top bar which I don't want.
Is there anyway I could use ordinary UIViewController instead of UINavigationController?
P.S : it is a sample code I found [Here][1]
protocol Coordinator {
    func start()
}
protocol FlowACoordinatable {
    var coordinator: FlowACoordinator
}
class FlowACoordinator: Coordinator {
private var navigationController: UINavigationController

private var firstVC: FirstViewController
private var secondVC: SecondViewController

init(navigationController: UINavigationController) {
    self.navigationController = navigationController
}

func start() { ... }

func present(_ viewController: (FlowACoordinatable & UIViewController)) {
    viewController.coordinator = self
    self.navigationController.pushViewController(viewController, animated: true)
}

...

}
class FirstViewController: UIViewController, FlowACoordinatable {
var coordinator: FlowACoordinator?

func buttonTapped() {
    self.coordinator?.goToNextStep()
}

}

A: Answering my own question...
Coordinators architecture is based on UINavigationController and can not be replaced by UIViewController.
But still, it is possible to hide the buttom bar pane using Object Inspection and check Hide buttom bar... or do it by code.


text:
Q: Ayuda en Taller de Estudio Tengo un problema con mi codigo tengo que realizar este trabajo, y no puedo calcular los valores totales leyendo un archivo externo, con estas caracteriticas en Java.

Llevo este codigo trabajado, que me calcula los valores del puntaje de los competidores pero todos en array unidimensional, pero el el calculo total de cada uno, ahí estoy medio mareado.
ucn es la librería de la Universidad que modifica algunas sentencias de java.
Saludos
import java.util.Arrays;
import ucn.*;
public class TallerTP {

   String Paises[] = new String[8];
   String Pilotos[] = new String[8];
   double Horas[] = new double[8];
   int Puntaje[] = new int[8];
   String PilotosPuntaje[][] = new String[8][2];

  public static void main(String[] args) {
    TallerTP pv = new TallerTP();
    pv.cargar();
    //StdOut.println("Ordenados Paises");
    //pv.ordenarPaises();
    //pv.imprimir();
    StdOut.println("Ordenados Horas");
    pv.ordenarHoras();
    pv.puntaje();
    pv.imprimir();
  }

  public void cargar(){
  In entrada=new In ("wrc.txt");

    while(!entrada.isEmpty()){
      for(int i=0; i<8; i++){
        Paises[i] = entrada.readString();
        Pilotos[i] = entrada.readString();
        Horas[i] = entrada.readDouble();
       }
    }
   entrada.close();
  }

//  public void ordenarPaises(){
//    for(int k=0; k<Paises.length; k++){
//      for(int f=0; f<Paises.length-1-k; f++){
//        if (Paises[f].compareTo(Paises[f+1])>0){
//          String auxpais;
//          auxpais = Paises[f];
//          Paises[f] = Paises[f+1];
//          Paises[f+1] = auxpais;
//          String auxpiloto;
//          auxpiloto = Pilotos[f];
//          Pilotos[f] = Pilotos[f+1];
//          Pilotos[f+1] = auxpiloto;
//          double auxhoras;
//          auxhoras = Horas[f];
//          Horas[f] = Horas[f+1];
//          Horas[f+1] = auxhoras;
//        }
//      }
//    }
//
//  }

   public void ordenarHoras(){
    for(int k=0; k<Horas.length; k++){
      for(int f=0; f<Horas.length-1-k; f++){
        if (Horas[f]>Horas[f+1]){
          double auxhoras;
          auxhoras = Horas[f];
          Horas[f] = Horas[f+1];
          Horas[f+1] = auxhoras;
          String auxpais;
          auxpais = Paises[f];
          Paises[f] = Paises[f+1];
          Paises[f+1] = auxpais;
          String auxpiloto;
          auxpiloto = Pilotos[f];
          Pilotos[f] = Pilotos[f+1];
          Pilotos[f+1] = auxpiloto;
        }
      }
    }

  }

   public void puntaje(){
     String p = Paises[0];
     String t = Pilotos[0];
     int x = 0;
     int a = 0;
     int c = 0;
     int Puntos[] = {25,18,15,12,10,8,6,4,2,1};
      for (int k=0; k<Puntaje.length; k++) {
        if (c < 10 && p.equals(Paises[k])) {
          p = Paises[k];
          Puntaje[k] = Puntos[c];
          c = c + 1;
        }else{
          c = 0;
          Puntaje[k] = Puntos[c];
          p = Paises[k];
          c = c + 1;
        }
      }
   }

  public void imprimir() {
    for(int f=0; f<Paises.length; f++){
     StdOut.println(Paises[f] + " - "+ Pilotos[f] +" - "+ Horas[f] +" - "+Puntaje[f]);
    }
     //for(int d=0; d<PilotosPuntaje.length; d++){
     //StdOut.println(PilotosPuntaje[d][0] +" - "+ PilotosPuntaje[d][1]);
    // }
  }

}

A: En el método puntaje() tenés las variables t, x y a que no se usan nunca.
Además la condición p.equals(paises[k]) sólo se cumple cuando hay dos paises iguales seguidos porque le estás volviendo a asignar a p el mismo valor que tiene, y si no se cumple le pasa a puntaje[k] el primer valor de puntos[] porque c vale cero.
Igual puntaje[] no haría falta ordenarlo porque los valores son fijos. Si lo que querés es que te devuelva los tres primeros puestos de algún país, podrías guardar el nombre del país en una variable afuera del ciclo y después de ordenarlos recorrer el arreglo hasta que el país[k] coincida tres veces con esa variable.


text:
Q: How can we feed our custom synonym word list to NLP model (Word2Vec is preferred) I am using Word2Vec  model for making a vectorizer from my data.
My data has custom/business defined synonym word list which i want my NLP model should consider.
For e.g if "A" is a synonym of "B" then if i try to find synonym word for "A" using Word2Vec then it should give "B" with 100% match.
I can try different NLP models as well provided i am able to achieve the above requirement.

A: Since your synonym list is very small, I'd recommend you train your model, then loop through your synonym list, reassigning the word vector of each synonym in your model (and adding any that were not present in your training data). This of course destroys any information about the learned word vectors, which depending on your use case may be a problem.
Some alternative approaches:

*

*Reassign word vectors to a composite of their constituent synonyms (e.g. mean). Unfortunately this works best if your synonyms already had similar vectors, which I assume is not the case. In general this probably loses more semantic information than it preserves.

*Add synonyms as duplicate words, (ie,a given word will have two vectors, one inferred from the training data and one equal to it's synonym). This preserves semantic relationships but creates ambiguity whenever you need to perform a computation using a vector that could have a synonym. How big of an issue this is depends on your use case.

*Apply a projection to your word embeddings subject to certain constraints (synonym equality). I've never tried this so I'm unsure how it impacts your model, how difficult it would be to compute, or what objective function you'd need to optimize.

*Preprocess your text. Yes, it'll take a while, but compute is cheap these days.


text:
Q: How to get the value of date_select field in Rails? I need to get the value of the date_select field in my controller. I also need to add an if statement so that if the value is nil it won't try to get the data and trow an error.
Here's my date_select field :
<%= date_select :regdate, :date, order: [:year, :month] %>

Here's the params in the debug :
regdate: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
  date(3i): '1'
  date(1i): '2014'
  date(2i): '10'

A: In the controller side
regdate =  Date.new(params["regdate(1i)"].to_i,
                    params["regdate(2i)"].to_i,
                    params["regdate(3i)"].to_i)

or this, whatever coming in your params
regdate =  Date.new(params["date(1i)"].to_i,
                    params["date(2i)"].to_i,
                    params["date(3i)"].to_i)

A: I think this notation looks nicer in code:
foo = Date.new(*params[:foo].map { |_, v| v.to_i })

That requires you to set the prefix option in date_select, which moves all inputs for year, month and day into an hash:
<%= f.date_select 'start_date', prefix: 'foo'} %>

A: In the controller use
@regdate = params

And inner the view
<%= @regdate["regdate"]["date(3i)"]  %>
<%= @regdate["regdate"]["date(2i)"]  %>
<%= @regdate["regdate"]["date(1i)"]  %>

A: I found date_select to be a bit tricky because of the format of the params it will generate, but to use the question at hand, here's a full explaination. Starting with the view:
# View
= date_select :regdate, :date, order: [:year, :month]

Above code will give a Year and a Month selector. So in the params that will be passed to the backend/rails app:
# Console
Parameters: {"utf8"=>"✓", "regdate"=>{"date(3i)"=>"1", "date(1i)"=>"2014", "date(2i)"=>"3"}, "commit"=>"Send"}

You are only looking for the first two values: Year, month
In backend/controller use following code to convert the params back into a date of any kind:
# Controller
selected_date =  Date.new(
  params[:download_date]["download_date(1i)"].to_i,
  params[:download_date]["download_date(2i)"].to_i
  ).strftime("%Y%m%d")

Note that attaching .strftime("%Y%m%d") at the end of the Date object will let to format the resulting date in any way you like. In this case it will result in:
201403


text:
Q: Value cannot be null c#.net I am creating a simple project on c#.net. I want to put the AutoNo textbox in my program. I have put but it is not working. it shown the error while ran program error said that

Value cannot be null Parameter name: Stringmscorlib

Code what I tried I attached below
   public void Load()
{
    SqlConnection Con = new SqlConnection("Data Source=.;Initial Catalog=test1;Persist Security Info=True;User ID=sa;Password=admin123");
    Con.Open();
    cmd = new SqlCommand("select id from records", Con);
    Data = cmd.ExecuteReader();
    while (Data.Read() != false)
    {

        auto = int.Parse(Data[0].ToString());

    }
    try
    {

        int newid = auto;
        int id = newid + 1;
        this.textBox1.Text = "S00" + id.ToString();

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message + ex.Source);
    }

    Data.Close();
}

}

A: There are two problems I can see here; the first would be: what if there are zero rows? what is auto then? is it null? then int.Parse(null) will fail. You don't actually show where auto is declared, which makes this bit a little hard to intuit about.
The other possibility is here:
auto = Data.GetString(0);

in which case: this is simply a null database value. Check for that, and handle it:
if (Data.IsDBNull(0))
{ ... do whatever; perhaps just "continue" }
else
{
    auto = Data.IsDBNull(0);
    // and process it, etc
}

But frankly, you're making life hard for yourself here; here's the same thing with a tool like Dapper:
using (var conn= new SqlConnection("...whatever..."))
{
    // here we're asserting *exactly* zero or one row
    string auto = conn.QuerySingleOrDefault<string>("select id from records");

    if (auto == null)
    { ... do something else? ... }
    else
    {
        var newid= int.Parse(auto);
    }
}

Note: your query could currently return any number of rows; since the code only processes the last value, I suggest that the SQL needs fixing; perhaps MAX, MIN, or TOP 1 with an ORDER BY clause; i.e. something like select MAX(id) as [id] from records. Note, however, that this sounds like a scenario where you should probably have used SCOPE_IDENTITY() in some query that added or inserted the value. And an id should very rarely be a string.

A: Parse method is not able to handle null value. Assuming auto is variable name.
instead of this
 int newid = Int32.Parse(auto);

use something like below
int newid=0;
int.TryParse(auto, out newid);


text:
Q: PHP script doesn't import CSV into MySQL # download the file off the internet
    $file = file_get_contents("http://localhost/sample.csv");
    $filepath = "C:/xampp/htdocs/test/file/sample.csv";
    file_put_contents($filepath, $file);
# load the data into sample table
    $pt1 = "LOAD DATA LOCAL INFILE ";
    $pt2 = "'/C:/xampp/htdocs/test/file/sample.csv' INTO TABLE sample ";
    $pt3 = "FIELDS TERMINATED BY ',' ENCLOSED BY '\"' ";
    $pt4 = "LINES TERMINATED BY '\r\n' ";
    $pt5 = "(col1,col2,col3,col4)";
    $sqlquerynew = $pt1.$pt2.$pt3.$pt4.$pt5;
    mysql_query($sqlquerynew);

This piece of code works on non-csv (well, I tested it with a text file instead).
Before this part gets run, I have to create a table. The table is now created, but no data is loaded. The file stated in the path exists.
What could be the problem?
Thanks
This is a sample csv I found online
"REVIEW_DATE","AUTHOR","ISBN","DISCOUNTED_PRICE"
"1985/01/21","Douglas Adams",0345391802,5.95
"1990/01/12","Douglas Hofstadter",0465026567,9.95
       ....... etc

A: Two problems
$pt2 = "'/C:/xampp/htdocs/test/file/sample.csv' INTO TABLE sample ";

Remove the / in front of C.
and secondly,
$pt5 = "(col1,col2,col3,col4)";

Make sure you have the right name for the columns. If you want to import * all columns, just remove it. It is also a good idea to remove the header in your case, because removing $pt5 you will succeed, but the header row will be added to the table.


text:
Q: My Angular tag input matInput not working I using angular/material version 10.2.3 and angular version 10.1.4.
Here my code sample:
<mat-form-field>
  <mat-label>Test Label:</mat-label>
  <input matInput>
</mat-form-field>

but its visual output isnt the same what i found on documentary

and mine:

Why is that?


text:
Q: Android MediaPlayer setDataSource() Throwing IllegalStateException Error While I use almost the same code to play two videos, the first works perfectly, but the second does not.  When I press the next video button, the program crashed with:
WARN/System.err(15726): java.lang.IllegalStateException
WARN/System.err(15726):     at android.media.MediaPlayer.setDataSource(Native Method)

Source code:
the first play code:
    mediaPlayer = new MediaPlayer();
    playURI = receiveIntent.getStringExtra("playURI");
    showDebugInfo("play uri "+playURI);
    Log.e("Gplayer on create", "play uri "+playURI);
    try {
        mediaPlayer.setDataSource(playURI);
    } catch (IllegalArgumentException e) {
        Log.v(LOGTAG, e.getMessage());
        finish();
    } catch (IllegalStateException e) {
        Log.v(LOGTAG, e.getMessage());
        finish();
    } catch (IOException e) {
        Log.v(LOGTAG, e.getMessage());
        finish();
    }

when press next button it runs the following code:
   String uri = listAdapter.getItem(position).getItem().getFirstResource().getValue();
    showDebugInfo(" Uri "+uri);
    if(mediaPlayer != null){
        mediaPlayer.stop();
    }
    try {
        mediaPlayer.reset();
        mediaPlayer.setDataSource(uri);
        mediaPlayer.prepareAsync();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        finish();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        finish();
    }

Why does this happen? and I check the two parts only the different that, the first one is new a mediaplayer and the second is let the mediaplayer stop and reset then the same.

A: I had the same problem.
You need to call mediaPlayer.reset(); before you are calling in the second video mediaPlayer.setDataSource(uri); the reason is, because the function mediaPlayer.setDataSource(uri); can be called only on idle state, and mediaPlayer.reset(); is the function that take you to idle state.
I understand it from this answer, even though the question is a bit different.


text:
Q: A fallacious argument concerning certain topological groups Let $K$ be a non-Archimedean local field, and let $\mathcal{O}$ be its ring of integers. Let $U$ be the group of $4 \times 4$ unipotent upper-triangular matrices over $K$. Consider the topology on $K$ induced by its normalized absolute value, and identify $U$ with the product space $K^6$ e.g. by the map
$$
 \begin{pmatrix}
1 & u_{12} & u_{13} & u_{14} \\
 & 1 & u_{23} & u_{24}\\
& & 1 & u_{34}  \\
 & & & 1
\end{pmatrix} \mapsto (u_{12},u_{13},u_{14},u_{23},u_{24},u_{34})$$
Then $U$ is a locally profinite group with respect to the topology induced by $K^6$. Now, fix $a \in K$ with $a \neq 0$. Since $\mathcal{O}$ is compact and open in $K$, the set
$$
N:=\left\{ \begin{pmatrix}
1 & 0 & a\alpha & 0 \\
  & 1 & \alpha & 0 \\
  & & 1 & 0 \\
  & & & 1
\end{pmatrix} : \alpha \in \mathcal{O} \right\}
$$
is a compact open subgroup of $U$. On the other hand, the subgroup
$$
L:= \begin{pmatrix}
1 & 0 & 0 & * \\
  & 1 & * & * \\
  & & 1 & * \\
  & & & 1
\end{pmatrix}
$$
is closed in $U$, so that $L \cap N$ is a compact open subgroup of $L$. But
$ L \cap N =\{I_4\}$, which implies that $L$ is discrete. In particular, the "root" subgroup
$$X:= \left\{ \begin{pmatrix}
1 & 0 & 0 & 0 \\
  & 1 & \alpha & 0 \\
  & & 1 & 0 \\
  & & & 1 \end{pmatrix} : \alpha \in \mathcal{O} \right\}$$
is contained in $L$, and so it is also discrete with respect to the subspace topology. As $X$ is homeomorphic to $\mathcal{O}$ and $\mathcal{O}$ is compact, this implies that $\mathcal{O}$ must be finite. But this is absurd (e.g. take the field $K=\mathbf{Q}_p$ of $p-$adic numbers, whose ring of integers $\mathcal{O}$ is the ring $\mathbf{Z}_p$ of $p-$adic integers).
I stumbled upon this by accident, and I'm desperately struggling with finding the error.
Thank you in advance.

A: Sorry maybe I misunderstood your notations, but what is your I_4 ? the identity matrix ? If so you don't get $L\intersect N = I_4$


text:
Q: Swift development pods is there some good tutorial where I can follow, is there a good tutorial for better understanding, the ones I find i just create the pod and them publish, there is no implementation for me start to develop my own

A: This is a poorly formed question... But if you're asking how to use podfiles, this video works great: https://www.youtube.com/watch?v=MuMZZtQpB6Y
If you're trying to make a podfile, here you are: https://guides.cocoapods.org/making/making-a-cocoapod.html


text:
Q: Improve Performance of categorical crossentropy on four dimensional prediction and target I have a Neural Network implemented in tensorflow that takes a batch of images and predicts a tensor with shape (batch_size, 9, 9, 10)
For each image in the batch the target (and the prediction) looks like this.
We predict an image with width 9, height 9 and depth 10. The depth of every pixel corresponds to a class so we have 10 classes.
So e.g. the prediction of pixel(0,0) with softmax looks like this [0, 0.8 ,0 ,0 ,0 ,0 ,0.2 ,0 ,0,0]
and the target of the pixel(0,0) looks like this [0, 1,0,0,0,0,0,0,0]
I want to use the classical cross entropy between these two tensors.
currently my loss is implemented like this:
def calculate_loss(prediction, target):
    '''
    prediction and target have shape (batch_size, 9, 9, 10)
    '''
    loss = 0
    for batch in range(0, BATCH_SIZE):
        for width in range(0,9):
            for heigth in range(0,9):
                loss += tf.losses.categorical_crossentropy(target[batch][width][height] , prediction[batch][width][height])
return loss

But with a high batch size (1024) this calculation takes 20 seconds.
And this is just way too slow.
Are there any already implemented functions in tensorflow/keras that can improve the performance of this loss?
Or do you know if I can change the code to improve performance?

A: tf.nn.softmax_cross_entropy_with_logits(target, prediction)

Is the answer.
I can then reduce sum the values of the output to get the same thing.
Don't forget to remove the sofmax layer in your model.


text:
Q: Typescript allowing variables to pollute global scope It seems that TypeScript is allowing variables from other files to pollute the global namespace. Or, at least, where I would expect definition errors to take place before runtime, they don't.
Consider these two files:
/* file1.ts */

const SomeVar = 'Hi'

/* file2.ts */

console.log(SomeVar)

In VsCode, I would expect an error in file2.ts as I have neither exported the const from file1.ts, nor have I imported it. When I run the node program, I do indeed get a runtime error, but this means that VsCode is giving a false positive by not throwing a linting error.
Note that there is no error under SomeVar in VsCode:

Is there a reason why variables aren't being scoped to their files for the linter in TypeScript?

A: You might need to install a linter extension for vscode, tslint for example.