text:
Q: Add Shopping cart block to cms page I would like to add a shopping cart block a cms page, but whenever I try, nothing happens...not even an error.
I've tried following this tutorial, http://www.magento.cc/how-to-use-php-on-a-cms-page.html.
So I created the new folders in app/code/local and then a Test.php file, yet when I try to include
 {{block type="YourModule_Custom/test" my_param1="value 1" another_param="value 2"}}

in the cms page, nothing appears.
Here's my code in the Test.php page:
<?php
class YourModule_Custom_Block_Test extends Mage_Core_Block_Abstract
{
    protected function _toHtml()
    {
        echo 'TEST';
        $this->getChildHtml('header');
        return $html;
    }
}

A: You can do a local.xml update.  And place your content as .phtml file
<cms_index_index>
    <reference name="content">
        <block type="Your_custom/Block" name="home_main" as="home_main" template="cms/default/home.phtml">
        </block>
    </reference>
</cms_index_index>

Create a file named home.phtml in cms/default/   Then you can use your own block type to use your custom module / functions
Then add your home page content in there.

A: I don't know what are you trying to achieve. But from your question, I have a strong feeling that, you are trying to set a template of your own through CMS page. If that is the case, let us analyze why your block didn't show any output.
Your block definition is like this
{{block type="YourModule_Custom/test" my_param1="value 1" another_param="value 2"}}

There is no problem with this defintion. But it is good, if you add name to your block. If you set a template along with that, then you don't need any backend code for setting a template for your block. That is your block should look like this
{{block type="YourModule_Custom/test" name="test.block" template="test.phtml"}}

Now when magento encounter this, it will find your block, set described name to that block (for later reference this name will be used. However it is not relevant in this case), set template specified to your block and then render the content in that template.
So you should have a block of type that you specified. You had it right now(you dont need that _toHtml() inside that). Along with that you need a template file test.phtml and it should be in the location app/design/frontend/<your_package>/<your_theme>/template/test.phtml. You dont have that file right now. So create it and add this content inside that file

<?php echo "I am here. Can you see me ?"; ?>

Now check your CMS page output. You can see that content. Isn't it ?
So right now what you are  trying to do is, instead of setting a template along with that block definition, you are trying to set it through your block. Is it wrong ? Obviously, NO. There are some cases, where we need to go with that way. I assume you really need it. So again let us redifine our block in this form.
 {{block type="YourModule_Custom/test" name="test.block"}}

Hmm. Here we didn't set a template to this block right now. You can hence set it through your block definition. You used _toHtml() method.
<?php
class YourModule_Custom_Block_Test extends Mage_Core_Block_Abstract
{
    protected function _toHtml()
    {
        echo 'TEST';
        $this->getChildHtml('header');
        return $html;
    }
}
?>

This method is using to set a template and then renders the content. So you are in the right track. But the problem here is, you are not setting any template!! plus your method returns a variable $html which holds nothing. So what should we return through a _toHtml() ? The answer lies in Mage_Core_Block_Template. Let us look on _toHtml() definition
protected function _toHtml()
{
    if (!$this->getTemplate()) {
        return '';
    }
    $html = $this->renderView();
    return $html;
}

Basically what this does is, it checks whether a template is set , if not return nothing. If it does renders it. That means, it is obvious that we need to set a template. So your block should look like this.
<?php
class YourModule_Custom_Block_Test extends Mage_Core_Block_Template
{
    protected function _toHtml()
   {
       $this->setTemplate('test.phtml');
       $html = parent::_toHtml();
       return $html;
   }
}

Note that your block extends from Mage_Core_Block_Template rather from Mage_Core_Bock_Abstract. This is because setTemplate() method is defined in Mage_Core_Block_Template class. In _toHtml(), we are setting our template and then leave rest to our parent block. Now check whether content in test.phtml is showing in your CMS page. It does right ?

A: I don't understand exact what do you want. but by your question my understanding is you want to display shopping cart block into any CMS page like Home page, About us page etc.
If my understanding is right then here is one solution for you.
You can insert this code into your cms page from admin.
Admin -> CMS -> Pages -> Select any page on which you want to display block -> Click on design tab from left navigation ->Under Page Layout section insert the below code in "Layout Update XML" field. Click on save.
<reference name="content">
        <block type="checkout/cart" name="checkout.cart">
            <action method="setCartTemplate"><value>checkout/cart.phtml</value></action>
            <action method="setEmptyTemplate"><value>checkout/cart/noItems.phtml</value></action>
            <action method="chooseTemplate"/>
            <action method="addItemRender"><type>simple</type><block>checkout/cart_item_renderer</block><template>checkout/cart/item/default.phtml</template></action>
            <action method="addItemRender"><type>grouped</type><block>checkout/cart_item_renderer_grouped</block><template>checkout/cart/item/default.phtml</template></action>
            <action method="addItemRender"><type>configurable</type><block>checkout/cart_item_renderer_configurable</block><template>checkout/cart/item/default.phtml</template></action>

            <block type="core/text_list" name="checkout.cart.top_methods" as="top_methods" translate="label">
                Payment Methods Before Checkout Button
                <block type="checkout/onepage_link" name="checkout.cart.methods.onepage" template="checkout/onepage/link.phtml"/>
            </block>

            <block type="page/html_wrapper" name="checkout.cart.form.before" as="form_before" translate="label">
                Shopping Cart Form Before
            </block>

            <block type="core/text_list" name="checkout.cart.methods" as="methods" translate="label">
                Payment Methods After Checkout Button
                <block type="checkout/onepage_link" name="checkout.cart.methods.onepage" template="checkout/onepage/link.phtml"/>
                <block type="checkout/multishipping_link" name="checkout.cart.methods.multishipping" template="checkout/multishipping/link.phtml"/>
            </block>

            <block type="checkout/cart_coupon" name="checkout.cart.coupon" as="coupon" template="checkout/cart/coupon.phtml"/>
            <block type="checkout/cart_shipping" name="checkout.cart.shipping" as="shipping" template="checkout/cart/shipping.phtml"/>
            <block type="checkout/cart_crosssell" name="checkout.cart.crosssell" as="crosssell" template="checkout/cart/crosssell.phtml"/>

            <block type="checkout/cart_totals" name="checkout.cart.totals" as="totals" template="checkout/cart/totals.phtml"/>
        </block>
    </reference>

After that you will see shopping cart block on your CMS page. If you don't need any block from them you can remove that blck from the above code.

A: if you try to call add to cart from cms page then add url like
checkout/cart/add?product=$id&qty=$qty

Example-


text:
Q: Problema em inserir registros no Oracle Estou tendo problemas para inserir registros no Oracle, abaixo segue o insert que utilizo:
insert into COMPRAS (id, valor, data, observacoes, recebido)
values (id_seq.nextval, 200, '19-FEB-2008', 'MATERIAL ESCOLAR', '1');

Entretanto gerou esse erro SQL;
 Erro ao iniciar na linha 1 no comando
    insert into COMPRAS (id, valor, data, observacoes, recebido)
    values (id_seq.nextval, 200, '19-FEB-2008', 'MATERIAL ESCOLAR', '1')
    Relatório de erro:
    Erro de SQL: ORA-01858: foi localizado um caractere não numérico onde se esperava um numérico
    01858. 00000 -  "a non-numeric character was found where a numeric was expected"
    *Cause:    The input data to be converted using a date format model was
               incorrect.  The input data did not contain a number where
               anumber was required by the format model.
    *Action:   Fix the input data or the date format model to make sure the
               elements match in number and type.  Then retry the operation.

Minha tabela esta assim:
COMPRAS
Nome        Nulo     Tipo
----------- -------- ------------
ID          NOT NULL NUMBER
VALOR                NUMBER
DATA                 DATE
OBSERVACOES          VARCHAR2(30)
RECEBIDO             CHAR(1)

Foi criada assim a tabela:
create table compras (
    id number primary key,
    valor number,
    data date,
    observacao varchar2(30),
    recebido char check (recebido in(0,1)));

    CREATE SEQUENCE ID_SEQ;

Como faço para resolver isso?

A: Você está tentando inserir um VARCHAR em um campo DATE
converta em data utilizando TO_DATE conforme o comentário do Eduardo Almeida
TO_DATE('19-Feb-2008', 'DD-Mon-YYYY')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Anyway to set a default only when there is parse error for @value In Spring, you could use @Value("${num:123}") private int number; to inject the value number.
Clearly the default will work when there is no num field in the configuration file.
However, when there is a malformatted one. Spring will throw the error like:
09:54:28.392 [main] WARN org.springframework.context.annotation.AnnotationConfigApplicationContext - Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'valuesApp': Unsatisfied dependency expressed through field 'number'; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: "string"

I know you could make the value injected type as String, then manually convert it to Integer type (can catch error etc.). However, is there any more elegant way of handling case like this? Such that Spring will use the default value in case of configuration file's one is malformatted.


text:
Q: replaceWith doesn't work as expected in replacing attr value replaceWith doesn't work in replacing attr?
value

$('.js').attr('href').replaceWith('#');

I want to replace the href value with #, is this a correct way?

A: Use .attr() to get/set attribute values:
 $('.js').attr('href','#')

A: Should work:
$('.js').attr('href','#')


text:
Q: First Four Words of Every Sentence, but Must Start With Word X and End With Word Y I wish to filter the first four words of every sentence, with the first word being "This" and last word being "on." I've been trying to watch YouTube tutorials, but all I could do was the following:
([A-Z](?:[^\s.!?]+(?:\s|\n)){0,4}(?:[^\s.!?]+)?)

Now, here is an example: This [perception rests] on...

A: The most basic regex would be
/\bThis\s+\w+\s+\w+\s+on\b/

which will match with no capturing. Perhaps what you consider a "word" character may differ from what the regex engine considers a word character.

A: You should consider using some NLP package to split text into sentences. Then use
^This\s+\S+\s+\S+\s+on\b

It matches a string that starts wth This, then has two words containing any non-whitespaces characters and then the word on.
See proof
EXPLANATION
NODE                     EXPLANATION
--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  This                     'This'
--------------------------------------------------------------------------------
  \s+                      whitespace (\n, \r, \t, \f, and " ") (1 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  \S+                      non-whitespace (all but \n, \r, \t, \f,
                           and " ") (1 or more times (matching the
                           most amount possible))
--------------------------------------------------------------------------------
  \s+                      whitespace (\n, \r, \t, \f, and " ") (1 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  \S+                      non-whitespace (all but \n, \r, \t, \f,
                           and " ") (1 or more times (matching the
                           most amount possible))
--------------------------------------------------------------------------------
  \s+                      whitespace (\n, \r, \t, \f, and " ") (1 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  on                       'on'
--------------------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char

A: (?:^|[.;!?]\s+)(\bThis\W*?(\b\w+\b)\W*?(\b\w+\b)\W*on\b)

Would something like that work. As far as I understand you want the sentence to have four words, start with "This" and end on "on".


text:
Q: How to update related data using entity framework 6 I have an entity Person, which has a related entity Hobby.  This is a many to many relationship where a person can have several hobbies, and a hobby can be associated with many people.  I want to create a ViewModel that allows new hobbies to be added and/or existing hobbies to be removed from a given Person entity.
The code below works, but I imagine it is rather inefficient.
var newHobbies = new List<Hobby>();

foreach (Hobby hobby in vm.Hobbies)
{
    var originalHobby = db.Hobbies.Find(hobby.HobbyID);
    newHobbies.Add(originalHobby);
}

originalPerson.Hobbies = newHobbies;

I prefer to do something like this:
var newHobbies = db.Hobbies.Where(x => vm.Hobbies.All(y => x.HobbyID == y.HobbyID)).ToList();
originalPerson.Hobbies = newHobbies;

But I get an error:

Only primitive types or enumeration types are supported in this
  context.

How can I update related data without going to the database multiple times?

A: The message says that you can't use vm.Hobbies inside a LINQ-to-Entities query, only primitive types. This is what you can do:
var hobbyIds = vm.Hobbies.Select(h => h.HobbyId).ToList();
var newHobbies = db.Hobbies.Where(x => hobbyIds.Contains(x.HobbyID)).ToList();

A: To avoid that exception you can select first the Ids from the vm.Hobbies collection and after that filter the hobbies you need:
var Ids=vm.Hobbies.Select(x=>x.HobbyID);

var newHobbies = db.Hobbies.Where(x => Ids.Contains(x.HobbyID)).ToList();
// another option could be: db.Hobbies.Where(x => Ids.Any(id=>id==x.HobbyID)).ToList();
originalPerson.Hobbies = newHobbies;

A: The overall construction would be like such:

*

*Your view takes the view model which displays the list of hobbies

*You have an action to add a new Hobby passing a Hobby entity back as part of the action

*You simply make a call back to the database to create the new association between the Person and Hobby

*Add the Hobby entity to the collection in Person

*Return passing the view model back to the view

In general EF and MVC are much easier to work with when you try to interact with your entities as whole entities and don't try to micromanage yourself things such as IDs, entity hydration, and so on.

A: You could join by ID instead of fetching data from the DB:
originalPerson.Hobbies = db.Hobbies.Join(vm.Hobbies, h => h.ID,
    v => v.HobbyID, (h, v) => h).ToList();


text:
Q: OpenMDAO: What are the pros and cons when comparing ScipyOptimizeDriver to pyOptSparseDriver? I learned in OpenMDAO: How to handle non-converging points in ExplicitComponent.compute? that pyOptSparseDriver enables handling of failed points in a way that ScipyOptimizeDriver doesn't. I also understand that the available optimization methods differ. What are other important differences between these two drivers?
In particular, what are the differences when using the "SLSQP" optimizer in each?

A: I have not quantified the detailed implementation differences between SLSQP in scipy and pyopt-sparse. However, I know they do differ a bit. The Scipy optimizer's line search is better about respecting bound-constraints than pyopt-spars's version of it.
The main difference is that the ScipyOptimizerDriver works with the pre-compiled optimizers in SciPy. On the other hand, you have to compile pyopt-sparse yourself.


text:
Q: XenServer 6.2: unable to detach NFS mount We recently lost an NFS server. It was used to export a drive with ISO files for use in XenServer patching / updating / etc. The server has been replaced but the mounted drive can't be removed from XenCenter or via the command line.
What I've tried:
(using these instructions):

*

*xe sr-list name-label=<NFS mount>

*xe pbd-list sr-uuid=<UUID of volume>

*xe pbd-unplug uuid=<UUID of mount point>

Error message:
Error code: SR_BACKEND_FAILURE_140
Error parameters: , Incorrect DNS name, unable to resolve.,
The volume no longer appears in /etc/mtab but Xen refuses to let go of it.
Suggestions on where else to look?

A: FWIW: I added an entry in /etc/hosts to point to the new (replacement server). Then the sequence of commands above will work and you can proceed to the 'forget' option in XenCenter.
If you are hitting this problem but getting the "General backend error" message try this. Essentially you'll need to get rid of the mounted volume on your own and then clean up Xen.


text:
Q: jquery select iframe children I am using the editArea library and jquery to do what i need...
http://www.cdolivet.com/index.php?page=editArea&sess=2b8243f679e0d472397bfa959e1d3841
so in my html there is an iframe tag that editArea uses what i need is to access something like so with jquery
$('iframe textarea').keydown(function (e){
   number = 17; //any number really :)
    if(e.which == number){
        //do something...
        alert('Done...');
    }
});

I tried the above but it looks like it is not detecting that key. but it works if selector was $(document)
therefore the rest of the function works it's just it's not picking up the iframes textarea keydown
any ideas?
Thanks

A: You need search within the inner document of the iframe, in order to get the textarea element:
var textarea = $('textarea', $('iframe').get(0).contentWindow.document);
textarea.keydown(function (e){
   var number = 17;
   var code = (e.keyCode ? e.keyCode : e.which);

    if(code == number){
        //do something...
        alert('Done...');
    }
});

A: $("iframe").contents().find("textarea").keydown(...)

A: You can travel any level, The above answers are correct. I did as below
var iframeMain = $("#iframe0").contents().find('#iframeMain');
var detailsForm = $(iframeMain).contents().find('#detailsform');

for accessing parents you can use
window.parent.parent. // upto any level

A: You need to access the iframes contentWindow.document, not the iframe itself.

A: You should be doing

iframeDoc = document.getElementById('resultsFrame').contentWindow;
// result frame is id of iframe
$(iframeDoc).keydown(function(e))
{
// your functionality here
}

A: If all else fails, I ended up getting the above to work by wrapping in this function:
$(window).blur(function () {
  // genius code here
}

A: Below code helped me.
$(document).ready(function(){
var iFrameDOM = $("iframe#frameID").contents();

iFrameDOM.find(".page").css("background-color", "#fff");

});


text:
Q: How to set custom claims to aad token using C# code I have a webapi which generates aad token and I have written token generation logic in Get() method in webapi.
I'm able generate aad jwt token from webapi get() method but, now I want to include some custom claims into the token.
How can I set custom claims to aad token using c#.
I have used below code for generating aad token.
var authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext("https://login.windows.net/" + ConfigurationManager.AppSettings["TenantID"].ToString());
            var credential = new ClientCredential(clientId: ConfigurationManager.AppSettings["ClientID"].ToString(), clientSecret: secret);
            var result = await authenticationContext.AcquireTokenAsync(
                ConfigurationManager.AppSettings["Resource"].ToString(),
                credential
                ).ConfigureAwait(false);

Kindly share any sample  c# code to set custom claims to aad token generated from above code .
Note: I want to set a new custom claim for aad token where custom claim value obtained from external logic.
Update 1:
Looks like below post may be useful.
https://www.rahulpnath.com/blog/azure-ad-custom-attributes-and-optional-claims-from-an-asp-dot-net-application/
I tried below following above post.
Generated jwt token to call Graph API. But I got blocked at below code.
    var dictionary = new Dictionary<string, object>();
        dictionary.Add(employeeCodePropertyName, employee.Code);

//Here I can't use graphApiClient.Users because, I don't have any user info on my jwt token. It will be just Access token which as details related to aad application.I want to update extension attribute which is present in OptionalClaims -> Access Token of AAD Application Manifest.
        await graphApiClient.Users[employee.EmailAddress]
            .Request()
            .UpdateAsync(new User()
            {
                AdditionalData = dictionary
            });

How to update extension claim attribute present in access token of optional claims . I want to update through c# code.
How to do that. Kindly suggest.
Update 2:
I want to use code similar to below for updating custom extension claim attribute present in optional claims of azure ad app but UpdateAsync is not working.
await graphApiClient.Application[clientid]
            .Request()
            .UpdateAsync(new Application()
            {
                AdditionalData = dictionary
            });

At UpdateAsync(), I'm getting issue as below
Specified HTTP method is not allowed for the request

Kindly let me know the solution to add custom user defined claim to azure ad access token.
Note: Since, I want to update access token ,there will be not be any user info on access token. So, graphApiClient.Users[employee.EmailAddress]  won't work, as access token will not have any user info like EmailAddress
I have created extension claim attribute in azure ad ap manifest as below

I want to update extension claim attribute extension_clientid_moviename value dynamically with value obtained from external source through code. How to do that. Kindly suggest.
Update 3:
I have tried below code to update extension claim attribute present in Optional claims ID Token.
   await graphApiServiceClient.Users["abcd@hotmail.com"]
                .Request()
                .UpdateAsync(new User()
                {
                    AdditionalData = dictionary
                });

I am getting error as below
Code: Request_ResourceNotFound\r\nMessage: Resource '' does not exist or one of its queried reference-property objects are not present.

A: That is because you are using OAuth 2.0 client credentials flow to get access token :
https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow
That flow is  commonly used for server-to-server interactions  without immediate interaction with a user. So you can't find user information in access token .
The document you provided is adding User's extension property , update that value via Microsoft Graph :
await graphApiClient.Users[employee.EmailAddress]
    .Request()
    .UpdateAsync(new User()
    {
        AdditionalData = dictionary
    });

That email is not from access token , you should manually provide the user's email who  the api wants to update the properties value .
But since the property is a User's extension property ,  you can get the value from claims in ID token when user login with Azure AD in your client app . That claim won't include in access token which issued using client credential flow .

A: Regarding the issue in Update 3, we can not use the guest user email here. We should use ObjectId instead. That's why you got Request_ResourceNotFound error.
await graphApiServiceClient.Users["ObjectId"]
                .Request()
                .UpdateAsync(new User()
                {
                    AdditionalData = dictionary
                });


text:
Q: php mysql select dropdown selected and distinct query I am confused here.
$sql_n = mysql_query("SELECT * FROM table1 WHERE n='{$row['n']}'");
$row_n = mysql_fetch_array($sql_n);

$sql= mysql_query("SELECT DISTINCT p FROM table1");
while($row = mysql_fetch_array($sql)) {

    if($row['p'] == $row_n['p']) {
        $selected = " selected";
    }

    $np .= "<option value='{$row['p']}'$selected>{$row['p']}</option>";
}

When i use query SELECT DISTINCT p, $selected isn't working, however if i use SELECT p. Its working, any idea why?

A: Without doing PHP, but knowing how engines will sometimes make up column names if you don't explicitly imply the "as" column name, it may be doing something with the distinct such as
select DISTINCT p as DISTINCT_P
and thus your column name "p" in the result query does't exist.
You may want to try
Select DISTINCT P P
so the implied result column name is "P" and qualify the rest of your routine.

A: My first reaction is that the solution to your problem would be to add DISTINCT in your first query as well.

A: Thinking it was the query, now I don't think that's it... but instead, your $selected variable.  Its not declared anywhere until the actual
if($row['p'] == $row_n['p']) {
        $selected = " selected";
    }

you probably need to "else" this and set
$selected = " ";
so it won't be a variable doesn't exist which is failing it when you are trying to concatinate it in the string building below when building out the OPTIONS list.


text:
Q: Animations: moving a UIView up and off the screen by its height - SWIFT I am trying to move a UIView up and off the screen by its height in ios.  Below is my code for doing this.  What I am finding is that the UIView does indeed move up and off the screen but instead of moving slowly as intended it continues to move off instantaneously without animation.  Please can someone advise?
 UIView.animate(withDuration: 300, animations: {
                    let heightOfViewContainingProgrBar = self.viewContainingProgressBar.frame.height
                    self.viewContainingProgressBar.topAnchor.constraint(equalTo: self.view.topAnchor, constant: -heightOfViewContainingProgrBar).isActive = true
                })

A: You need to put a call to layoutIfNeeded (for the view or one of it's superviews) inside the animation block.

A: Add
self.view.layoutIfNeeded()

inside animation block


text:
Q: adjusting Kalman estimates for no data I have a kalman filter like set up, when I get the current value of an observable process, and update my estimate of the state variable with it.
However, my observations are non-uniform in time, and I am trying to add the logic, that if the last observation was really long ago, I should forget about it, and use an a priori estimate X.
I can just switch to X, if time since the last observation is > T. But I was hoping to put in some general setting, which will be consistent with the Kalman filter logic. Does anyone have suggestions/references for it?
Many thanks.

A: If the Kalman filter-like model includes a covariance for the error-states, and if this covariance is being propagated in time such that it grows in the absence of new measurements, then a natural solution to the problem is to periodically check the trace of the error covariance against a ceiling threshold.  If the threshold is exceeded we assume the filter has lost all useful information about the state, and that the state estimate should be reset to the a-priori value.  Since the KF is usually a linearized approximation for a non-linear problem there is good reason to question the usefulness of the information stored in the covariance if the state error covariance is large.


text:
Q: mysql query to match some record where column contains multiple comma separated values I am working on a project.I have a table tblhomework which have a column students code-which contains students code separated by comma.Now I have few drop downs to search a record among which is search by student name.Now I have students code in my table how should I match it against the student name.I am using the following query,till now I am matching using students code but now I have to match by student name
Query
string studentcode = "%" + txt_studentcode.Text.ToString() + "%";
SELECT
tblhomework.ID,
tblteacher.TEACHERNAME,
tblclass.CLASSNAME,
tblhomework.Title,
tblhomework.HomeworkDetail,
tblhomework.StudentsCode
FROM tblhomework
join tblclass on tblclass.CLASSCODE=tblhomework.ClassCode
join tblteacher on tblteacher.TSHORTNAME=tblhomework.Tshortcode
where tblhomework.StudentsCode like'" + studentcode + "';

Following is the screenshot of the result I am getting

I have a student table which contains student names of students which you can use.

A: Using FIND_IN_SET in your current SQL:-
SELECT
    tblhomework.ID,
    tblteacher.TEACHERNAME,
    tblclass.CLASSNAME,
    tblhomework.Title,
    tblhomework.HomeworkDetail,
    tblhomework.StudentsCode
FROM tblhomework
JOIN tblclass ON tblclass.CLASSCODE=tblhomework.ClassCode
JOIN tblteacher ON tblteacher.TSHORTNAME=tblhomework.Tshortcode
WHERE FIND_IN_SET('" + studentcode + "', tblhomework.StudentsCode);

However, not this will only work if there are no spaces before / after the commas in the list of student codes
To join that against the student names table (and making assumptions on the layout of that table) use something like this:-
SELECT
    tblhomework.ID,
    tblteacher.TEACHERNAME,
    tblclass.CLASSNAME,
    tblhomework.Title,
    tblhomework.HomeworkDetail,
    tblhomework.StudentsCode ,
    tblstudent.StudentsName
FROM tblstudent
JOIN tblhomework ON FIND_IN_SET(tblstudent.StudentsCode, tblhomework.StudentsCode);
JOIN tblclass ON tblclass.CLASSCODE=tblhomework.ClassCode
JOIN tblteacher ON tblteacher.TSHORTNAME=tblhomework.Tshortcode
WHERE tblstudent.StudentsCode = '" + studentcode + "'

Searching by student name (although generally it would be easier if the drop down returned the numeric unique student id):-
SELECT
    tblhomework.ID,
    tblteacher.TEACHERNAME,
    tblclass.CLASSNAME,
    tblhomework.Title,
    tblhomework.HomeworkDetail,
    tblhomework.StudentsCode ,
    tblstudent.StudentsName
FROM tblstudent
JOIN tblhomework ON FIND_IN_SET(tblstudent.StudentsCode, tblhomework.StudentsCode);
JOIN tblclass ON tblclass.CLASSCODE=tblhomework.ClassCode
JOIN tblteacher ON tblteacher.TSHORTNAME=tblhomework.Tshortcode
WHERE tblstudent.StudentsName = '" + studentname + "'

A: To store comma separated values in column is bad design you should look at Database Normalization and do normalize your structure by storing all related student codes in a junction table,but as from above comments you said you can't change structure so in mysql you can use FIND_IN_SET() and join your students table ,i am not familiar with c# syntax so i have posted mysql query,also use your original name convention for the columns
SELECT
DISTINCT
  h.ID,
  t.TEACHERNAME,
  c.CLASSNAME,
  h.Title,
  h.HomeworkDetail,
  h.StudentsCode
FROM
  tblhomework h
  JOIN tblclass c
    ON c.CLASSCODE = h.ClassCode
  JOIN tblteacher t
    ON t.TSHORTNAME = h.Tshortcode
  JOIN students s ON(FIND_IN_SET(s.StudentsCode, h.StudentsCode) > 0)
WHERE  FIND_IN_SET('studentcode', h.StudentsCode) > 0
OR s.student_name LIKE 'test'

A: You can use 'FIND_IN_SET' function to search in comma separated set of values.
Change your where clause as below:
where FIND_IN_SET( @student_code, tblhomework.studentscode );

Use AddWithValue to bind value of 'studentcode' read from text box.
string studentcode = txt_studentcode.Text.ToString();
myCommand = new MySqlCommand( sql_query_string, connection );
myCommand.Parameters.AddWithValue( "@student_code", studentcode );

And execute.


text:
Q: Slide finger into buttons android How can I make it possible that when someone slides their finger into or over a button, the button acts as if it were getting pushed?
An example of what i'm looking for would be a keyboard app. Where you slide your fingers over all the keys to play sounds.

A: You can use an OnTouchListener like this:
    boolean firstTime = true;
    OnTouchListener testTouchListener = new OnTouchListener(){
        public boolean onTouch(View v, MotionEvent me){
            Rect r = new Rect();
            secondButton.getDrawingRect(r);
            if(r.contains((int)me.getX(),(int)me.getY())){
                //Log.i(myTag, "Moved to button 2");
                if(firstTime == true){
                    firstTime = false;
                    secondButton.performClick();
                }
            }
            if(me.getAction() == MotionEvent.ACTION_UP){
                //When we lift finger reset the firstTime flag
                firstTime = true;
            }
            return false;

        }
    };
    firstButton.setOnTouchListener(testTouchListener);

With this approach though you are going to get a flood of touch events because onTouch() gets called a lot with MotionEvent.ACTION_MOVE. So you'll have to keep a boolean that tells you if its the first time you've gotten onTouch() call. Then you can reset that boolean in onTouch() for MotionEvent.ACTION_UP so it works again the next time. However this could get kind of complicated if you are trying to do more than just 2 buttons. I think you'd have to keep a boolean for each of them seperately (or perhaps an array of booleans to hold them all). and you'd need an additional if(r.contains(x,y) statements for every button. This should get you started on the right path though.


text:
Q: Connection to mysql via php class DatabaseConnection{
  private $connection;
  private $username;
  private $password;
  private $serverName;
  private $database;
  private $database_found = false;

  //constructor with params
  public function __construct($database,$username,$password,$serverName){
    $this->$username = $username;
    $this->$password = $password;
    $this->$serverName = $serverName;
    $this->$database = $database;
  }

  //estabilish database connection
  public function connect()
  {
    $connection = mysql_connect($this->serverName,$this->username,$this->password);
    if($connection)
    {
      echo "Connection was successful!\n";
      $db = mysql_select_db($this->database,$connection);
      if($db)
      {
        echo "Database found!\n";
        $this->database_found = true;
      }
      else{
        echo "Database not found!\n";
      }
    }
    else {
      echo "Failed to connect to the database!\n";
    }
  }

  //closes connection
  public function close_connection(){
    mysql_close();
    echo "Connection closed!\n";
  }

  public function getConnection(){
    return $this->connection;
  }

  public function getDatabaseState(){
    return $this->database_found;
  }
}

This is my class for database connection. It connects to mysql, but for some reason it doesn't want to connect to the database (I've tried to insert database name as a string in mysql_select_database but still does not work). Database exist cause It was manually created. Thanks for the help.

A: You currently have:
$this->$username = $username;

this should be:
$this->username = $username;

You have 4 occurrences of this.

A: mysql_* functions are deprecated, you should rather use PDO. Here is the first tutorial I found.
You also use $this->$username where you should use $this->username. Here is the official tutorial about PHP classes.
Also, the convention is to write private variables in classes with an underscore at the start, like this:

*

*private $_username; to create it ;

*$this->_username to call it.

You can also create getters and setters to interact with your variables. (why?)

A: Check your access rights at MySQL.
 Is the user allowed to use the given DB?


text:
Q: JEE Architectural question: Service can inject Service? Or Service can inject only Dao? Here is a architectural problem while using Dao and Service and Controller:
Suppose that:
In DAO layer, there are DAO Classes called: Dao1, Dao2, ...
In Service Layer, there are Service Classes called: Service1, Service2, ...
In Controller Layer, there are Controller Classes called: Controller1, Controller2, ...
Service1 need to inject Dao1, and Service2
Controller1 need to inject Dao2, Service1 and Controller2
Does this architecture follow the JEE principales? Is there any issue?
It is better tp say that: Service can inject only Dao, and Controlleur can inject only Service?

A: As per my understanding, JEE does not mention/recommend the design patterns. JEE defines the set of APIs across different areas such as transactions, jdbc, jax-rs and so on and the implementation of these APIs is provided by different vendors. Thus JEE standards help develop an enterprise application but they do not dictate any design principles. So I guess that your question is whether this architecture follows good design patterns and if there is any issue.
Ideally as per your second question, a controller must not inject a dao class. A controller must only call services and the services should inject dao classes and call their methods. This design provides loose coupling between controller, service and dao layers. This way, if the signature of a dao class method changes, the controller layer is untouched and only service layer needs to change.
Generally speaking, most designs try to achieve loose coupling and high cohesion as much as possible.
Hope this helps!


text:
Q: Is there a way to increase the upper limit to iCloud storage space? I see here (bold my own):

With Apple One, you can choose a subscription plan that includes 50GB, 200GB or 2TB of iCloud storage. If you need more iCloud storage, you can buy more for a total of up to 4TB.

This seems to mean for people with more than 4TB of data (e.g. someone with lots of family videos, or a hobby photographer), there's simply no way to store it all in iCloud (without creating separate dummy accounts). Is there any way?
For reference, Google Drive goes up to 30TB

A: Before Apple One introduced 4TB iCloud storage plans, the limit was 2TB. There was no way to increase the limit past that biggest tier, and likewise now with the 4TB tier — there's no tier beyond the largest tier.
This has been a regular complaint of iCloud. The 4TB tier could have been in response to the years of asking for more than 2TB, but of course now we're in the same situation and delaying the inevitable for those of us who store a lot of data in iCloud.


text:
Q: Multiple threads with notifyAll() I'm writing a java program that print seconds elapsed, and every 5th second it will print a message. This is a sample output:
0 1 2 3 4 hello 5 6 7 8 9 hello 10 11 12 13 14 hello 15 16 17 18 19 hello

How can I remove the boolean variable printMsg? Is there a better thread design that allow this?
For now, without printMsg the program will print multiple "hello" during the 1/10 second program staying at 5, 10, 15 etc.
class Timer {
    private int count = 0;
    private int N;
    private String msg;
    private boolean printMsg = false;

    public Timer(String s, int N) {
        msg = s;
        this.N = N;
    }

    public synchronized void printMsg() throws InterruptedException{
        while (count % N != 0 || !printMsg)
            wait();
        System.out.print(msg + " ");
        printMsg = false;
    }

    public synchronized void printTime() {
        printMsg = true;
        System.out.print(count + " ");
        count ++;
        notifyAll();
    }

    public static void main(String[] args) {
        Timer t = new Timer("hello", 5);
        new TimerThread(t).start();
        new MsgThread(t).start();
    }
}

class TimerThread extends Thread {
    private Timer t;
    public TimerThread(Timer s) {t = s;}

    public void run() {
        try {
            for(;;) {
                t.printTime();
                sleep(100);
            }
        } catch (InterruptedException e) {
            return;
        }
    }
}

class MsgThread extends Thread {
    private Timer t;
    public MsgThread(Timer s) {t = s;}

    public void run() {
        try {
            for(;;) {
                t.printMsg();
            }
        } catch (InterruptedException e) {
            return;
        }
    }
}

A: One option to simplify and better design is to use single thread instead of two threads. And let the single thread take care of printing seconds as well as message. That way reduce one thread and don't need to wait() and notify. Is there is any reason why you want to use two threads? Code below:
public class Timer {
    private int count = 0;
    private int N;
    private String msg;

    public Timer(String s, int N) {
        msg = s;
        this.N = N;
    }

    public synchronized void printTime() {
        System.out.print(count + " ");
        count ++;
        if(count % N == 0) {
            System.out.print(msg + " ");
        }
    }

    public static void main(String[] args) {
        Timer t = new Timer("hello", 5);
        new TimerThread(t).start();
    }
}

class TimerThread extends Thread {
    private Timer t;
    public TimerThread(Timer s) {t = s;}

    public void run() {
        try {
            for(;;) {
                t.printTime();
                sleep(1000);
            }
        } catch (InterruptedException e) {
            return;
        }
    }
}

A: Don't need to use printMsg flag, just notifyAll when count % N == 0
public synchronized void printMsg() throws InterruptedException {
    wait();
    System.out.print(msg + " ");
}

public synchronized void printTime() {
    System.out.print(count + " ");
    count++;
    if (count % N == 0){
        notifyAll();
    }
}


text:
Q: Error in query ORA-00979: not a GROUP BY expression I have a query that worked for me when I was using Mysql.
Now I get this error on Oracle :
ORA-00979: not a GROUP BY expression

This is the query:
SELECT o.neNesId, COUNT(o)
FROM ParNe AS o
WHERE o.neBanId = :neBanId
GROUP BY o.neNesId

Any ideas why I have this error?

A: Your query is:
SELECT o.neNesId, COUNT(o)
FROM ParNe AS o
WHERE o.neBanId = :neBanId
GROUP BY o.neNesId

My guess is that o.o is not a valid field.  So, you have a table name where a column name is expected.
Try this instead:
SELECT o.neNesId, COUNT(*)
FROM ParNe AS o
WHERE o.neBanId = :neBanId
GROUP BY o.neNesId

Or replace the * with a valid column name.

A: use count(*) . count(o) is used in hibernate not in sql query

A: You need to select count(*) or count(1) as in Gordon's example. If you insist on using your query syntax, which is not necessary at all then try this:
SELECT neNesId, count(o) AS o_cnt
  FROM
  (  -- your query here --
   SELECT 1 neNesId, 2 AS o FROM dual
  )
  GROUP BY neNesId
  /


text:
Q: Why is SliverFillRemaining expanding too much? I'm trying to make a SliverAppBar that reacts to its height, showing different things depending if it's expanded or not.
I've based it on https://medium.com/flutter-community/flutter-sliverappbar-snap-those-headers-544e097248c0, but I'm having an issue:
The empty space at the end of the list is way too long.
Removing SliverFillRemaining is not necessary if the number of items is high, but changing the numberOfItems  to e.g. 3 items (instead of 30), the SliverFillRemaining is necessary.
Check out this dartpad for the code: https://dartpad.dev/2c434ddf2d4d1e87bd4b421f0a673c2d
      CustomScrollView(
        physics: AlwaysScrollableScrollPhysics(),
        controller: _controller,
        slivers: [
          SliverAppBar(
            pinned: true,
            backgroundColor: Colors.grey[100],
            stretch: true,
            automaticallyImplyLeading: false,
            flexibleSpace: Header(
              maxHeight: maxHeight,
              minHeight: minHeight,
            ),
            collapsedHeight: minimizedHeight,
            expandedHeight: maxHeight - MediaQuery.of(context).padding.top,
          ),
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                return _buildCard(index);
              },
              childCount: numberOfItems,
            ),
          ),
          SliverFillRemaining(
              hasScrollBody: true), // ** <-- this will add space, but too much **
        ],
      ),

A: if you are just adding a certain height of space, i suggest you use SliverToBoxAdapter:
SliverToBoxAdapter(
  child: SizedBox(
    height: 50,
  ),
),

A: make the hasScrollBody value to be false
like this:
     SliverFillRemaining(
        hasScrollBody: false
     ),


text:
Q: grid-template-areas doesn't work with ReactJS function components NOTE: You can view and edit the code in CodeSandbox.
I have the following parent component which contains 5 children, 3 of them are React components, while the remaining 2 are regular HTML buttons:
import "./App.css";
import React from "react";
import FormField from "./FormField";

export default function App() {
  return (
    <form className="Form">
      <FormField className="name" title="Name" type="text" isRequired={true} />
      <FormField className="salary" title="Salary" isRequired={true} />
      <FormField className="age" title="Age" type="text" isRequired={true} />
      <button className="submit">Submit</button>
      <button className="update">Update</button>
    </form>
  );
}

The CSS styling for the parent (App.css) is shown below (notice the grid-template-area property):
.Form {
  display: grid;
  grid-template-areas:
    "name name"
    "salary salary"
    "age age"
    "submit update";
  gap: 20px;
}
.name {
  grid-area: name;
}
.salary {
  grid-area: salary;
}
.age {
  grid-area: age;
}
.submit {
  grid-area: submit;
}

.update {
  grid-area: update;
}

I expect to see the following based on my grid areas:

But the actual result is:

Where is the problem that prevents my grid from matching the specified areas?

A: Wrap your FormFields in a div with the grid area class on them.
the FormField adds the class on the input, not itself.
<form className="Form">

<FormField title="Name" type="text" isRequired={true} />

<FormField title="Salary" isRequired={true} />

<FormField title="Age" type="text" isRequired={true} />

  <button className="submit">Submit</button>
  <button className="update">Update</button>
</form>


text:
Q: Temperature circuit not functioning I am attempting to help mentor some high school kids on circuits and obviously not doing a very good job.  We are trying to get a prototype PCB working that uses a max31856mud datasheet and k thermocouple to measure temperature everything appears to be set up great, but the microcontroller OLED is just reading 32F at all times.
This same setup was used on a breakout board using the same temperature IC and worked fine see the pictures below.  The only change seems to be the ground pin selected.  Does anyone see any potential problems?
I noticed this microcontroller has 5 ground pins should I expect connecting 1 to be sufficient?

A: The value of 32°F is 0°C, reading always zero likely means there is a problem with communication. Are you sure you have the SPI lines connected and set in software correctly?
On the breadboard, the break-out board has a different order of pins than the chip itself (CS is to the left of SDI, while on the schematic it is above SCK).


text:
Q: Invertir orden de elementos de una lista en Python Esta es mi primera pregunta y si no está fuera de las reglas, quisiera que me ayudaran a comprender este código, específicamente una linea. Estoy haciendo un curso de Python en Cisco. En el ejemplo que dejo abajo  se invierte el orden de los elementos de la lista. Entiendo que:" my_list[length - i - 1] " en cada iteración se refiere al último elemento, pero no entiendo por qué. ¿Sería 5 -i -1? ¿Como llega al ulitmo elemento con esto?
my_list = [10, 1, 8, 3, 5]
length = len(my_list)

for i in range(length // 2):
    my_list[i], my_list[length - i - 1] = my_list[length - i - 1], my_list[i]

print(my_list)

Gracias por su ayuda.

A: Como usar listas en Python
En este ciclo
for i in range(length // 2):
    my_list[i], my_list[length - i - 1] = my_list[length - i - 1], my_list[i]

estas haciendo un intercambio de variables. Esta expresión es del tipo
a, b = b, a

donde Python primero evuala el lado derecho, obteniendo los valores a y b. Luego de obtener los valores y guardarlos en variables temporales, procede al reemplazo de las variables en el lado izquierdo. No hay confusión, pues los valores ya están calculados.
my_list[i] obviamente es el elemento i-esimo desde el principio de la lista.
my_list[length - i - 1] es el elmento i-esimo desde el final. lenght - 1 es el índice del último elemento. Si le restamos i, que va de cero en adelante, iremos recorriendo del último hacia el primero.
Entonces, si ejecutamos manualmente la iteración, tenemos las siguientes asignaciones:
my_list[0], my_list[4] = my_list[4], my_list[0]
my_list[1], my_list[3] = my_list[3], my_list[1]

que intercambian los elementos de la lista.
Para aclarar el tema de los indices en Python,
Elemento por elemento
Puedes acceder a cualquier elemento usando la notación lista[x], donde 'x' es un valor entre 0 y n-1, siendo n el número de elementos en la lista.
También puedes usar indices negativos, que se cuentan desde el último elemento. Así, lista[-1] es el último elemento (n - 1), lista[-2] es el penúltimo (n - 2), etc.
Rebanada de listas
Puedes acceder a un rango de elementos (tajada, rebanada o slice) poniendo el indice de inicio y final separados por :. El rango no incluye el elemento señalado por el índice final.
En una rebanada de listas se pueden omitir los indices inicial y final. Si no se colocan, se usa cero y -1 respectivamente.
La expresión lista[1:3] produce una lista de 2 elementos:
my_list = [10, 1, 8, 3, 5]
print(my_list[1:3])

produce [1, 8].
Esto admite combinaciones. Por ejemplo, puedes usar indices negativos:
my_list = [10, 1, 8, 3, 5, 7, 10, 11]
print(my_list[1:-2])

produce [1, 8, 3, 5, 7].
Cambiando el orden
También puedes indicar un tercer parámetro en la rebanada que indica de cuanto en cuanto avanzar el indice que recorre la lista. Este parámetro también se separa con ":"
Si quieres recorrer los elementos de dos en dos, puedes usar
lista[::2]

Si el valor es negativo, entonces la lista se recorre en orden inverso
my_list = [1,2,3,4,5,6,7,8]
print(my_list[::-1])

produce [8, 7, 6, 5, 4, 3, 2, 1]
Si quieres procesar sólo una rebanada de la lista, debes invertir los indices de principio y final:
my_list = [1,2,3,4,5,6,7,8]
print(my_list[3::-1])

produce [4, 3, 2, 1]
Ojo: No pusimos el indice inicial y tomó por default el primer elemento de la lista, pero si pones explicitamente cero, no da igual:
my_list = [1,2,3,4,5,6,7,8]
print(my_list[3:0:-1])

produce [4, 3, 2] porque el proceso termina al llegar al indice final (cero en este caso), el que no se procesa.


text:
Q: postgres error for rails in ubuntu I was having a rails application, and I want to deploy it in my new laptop ( with ruby and rails installed fresh).
After installing gems and all .. when i goto my rails application folder and ruby rails s
Error shows like :
/home/insane/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.11/lib/active_record/connection_adapters/postgresql_adapter.rb:1208:in `initialize': FATAL:  role "insane" does not exist (PG::Error)
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.11/lib/active_record/connection_adapters/postgresql_adapter.rb:1208:in `new'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.11/lib/active_record/connection_adapters/postgresql_adapter.rb:1208:in `connect'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.11/lib/active_record/connection_adapters/postgresql_adapter.rb:326:in `initialize'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.11/lib/active_record/connection_adapters/postgresql_adapter.rb:28:in `new'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.11/lib/active_record/connection_adapters/postgresql_adapter.rb:28:in `postgresql_connection'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.11/lib/active_record/connection_adapters/abstract/connection_pool.rb:315:in `new_connection'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.11/lib/active_record/connection_adapters/abstract/connection_pool.rb:325:in `checkout_new_connection'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.11/lib/active_record/connection_adapters/abstract/connection_pool.rb:247:in `block (2 levels) in checkout'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.11/lib/active_record/connection_adapters/abstract/connection_pool.rb:242:in `loop'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.11/lib/active_record/connection_adapters/abstract/connection_pool.rb:242:in `block in checkout'
    from /home/insane/.rvm/rubies/ruby-2.1.0/lib/ruby/2.1.0/monitor.rb:211:in `mon_synchronize'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.11/lib/active_record/connection_adapters/abstract/connection_pool.rb:239:in `checkout'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.11/lib/active_record/connection_adapters/abstract/connection_pool.rb:102:in `block in connection'
    from /home/insane/.rvm/rubies/ruby-2.1.0/lib/ruby/2.1.0/monitor.rb:211:in `mon_synchronize'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.11/lib/active_record/connection_adapters/abstract/connection_pool.rb:101:in `connection'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.11/lib/active_record/connection_adapters/abstract/connection_pool.rb:410:in `retrieve_connection'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.11/lib/active_record/connection_adapters/abstract/connection_specification.rb:171:in `retrieve_connection'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.11/lib/active_record/connection_adapters/abstract/connection_specification.rb:145:in `connection'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.11/lib/active_record/model_schema.rb:308:in `clear_cache!'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.11/lib/active_record/railtie.rb:97:in `block (2 levels) in <class:Railtie>'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:418:in `_run__2015430698042624034__prepare__3529665547423141566__callbacks'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:405:in `__run_callback'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:385:in `_run_prepare_callbacks'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:81:in `run_callbacks'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/actionpack-3.2.11/lib/action_dispatch/middleware/reloader.rb:74:in `prepare!'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/actionpack-3.2.11/lib/action_dispatch/middleware/reloader.rb:48:in `prepare!'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/railties-3.2.11/lib/rails/application/finisher.rb:47:in `block in <module:Finisher>'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/railties-3.2.11/lib/rails/initializable.rb:30:in `instance_exec'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/railties-3.2.11/lib/rails/initializable.rb:30:in `run'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/railties-3.2.11/lib/rails/initializable.rb:55:in `block in run_initializers'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/railties-3.2.11/lib/rails/initializable.rb:54:in `each'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/railties-3.2.11/lib/rails/initializable.rb:54:in `run_initializers'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/railties-3.2.11/lib/rails/application.rb:136:in `initialize!'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/railties-3.2.11/lib/rails/railtie/configurable.rb:30:in `method_missing'
    from /home/insane/Rails/BACKUP/config/environment.rb:5:in `<top (required)>'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activesupport-3.2.11/lib/active_support/dependencies.rb:251:in `require'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activesupport-3.2.11/lib/active_support/dependencies.rb:251:in `block in require'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activesupport-3.2.11/lib/active_support/dependencies.rb:236:in `load_dependency'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activesupport-3.2.11/lib/active_support/dependencies.rb:251:in `require'
    from /home/insane/Rails/BACKUP/config.ru:3:in `block in <main>'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/rack-1.4.5/lib/rack/builder.rb:51:in `instance_eval'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/rack-1.4.5/lib/rack/builder.rb:51:in `initialize'
    from /home/insane/Rails/BACKUP/config.ru:in `new'
    from /home/insane/Rails/BACKUP/config.ru:in `<main>'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/rack-1.4.5/lib/rack/builder.rb:40:in `eval'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/rack-1.4.5/lib/rack/builder.rb:40:in `parse_file'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/rack-1.4.5/lib/rack/server.rb:200:in `app'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/railties-3.2.11/lib/rails/commands/server.rb:46:in `app'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/rack-1.4.5/lib/rack/server.rb:304:in `wrapped_app'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/rack-1.4.5/lib/rack/server.rb:254:in `start'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/railties-3.2.11/lib/rails/commands/server.rb:70:in `start'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/railties-3.2.11/lib/rails/commands.rb:55:in `block in <top (required)>'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/railties-3.2.11/lib/rails/commands.rb:50:in `tap'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/railties-3.2.11/lib/rails/commands.rb:50:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

I have gone through the below link , but even it dint help saying /Rails/BACKUP$ createdb insane
createdb: could not connect to database postgres: FATAL:  role "insane" does not exist
(postgreSQL error) FATAL: role "demo" does not exist (PG::Error)`
Please help

A: You need a user in the database named insane.
Open up a terminal and do the following
(the $ and psql> denote the terminal type, not commands that you type)
$ psql template1
psql> CREATE USER insane WITH PASSWORD 'some_password';

That should create the user for you. Alternatively, if this is on a dev machine, you can just use
psql> CREATE USER insane superuser;

That will create the user insane with all permissions.
NOTE
You may first need to be logged in as the postgres user.
$ sudo su postgres
<password for your account>

You will not see your password being typed.
Then you will be able to use the first set of commands above.


text:
Q: Is a non-orientable surface a kind of manifold? An example of a non-orientable surface is the Moebius Strip. Iam just curious whether it is indeed a manifold by definition.

A: Yes: a Möbius band is a manifold.
There are both orientable and non-orientable manifolds. The Klein bottle and the real projective plane are two other examples of non-orientable surfaces.
The definition of a manifold is a local one. The definition of orientability is a global one.

A: Yes, it is an open manifold. Orientability has nothing to do with it...

A: Yes, as a manifold or as a $\partial$-manifold, of two cases.


text:
Q: More efficient way to store Playing Cards in bits? I am currently helping teach a Computer Programming class. (I am in my Senior Year in High School, TA-ing for my Computer Programming teacher.) Right now the students are learning about bit-wise operators, but some more advanced ones are asking me about using bits and bit-wise operations to store data in the bits. So far what we they is pretty simple, but effective giving 50% (give or take 5%) compression rate. We take our playing card, let's say an Eight of Diamonds, and turn it into a 7 bit value 0b1011000. This works for all generic playing cards Ace - King, and all suits, and you can just put the bit (or integer) into a function and you will get a playing card back.
Here is what they have come up with so far.
0b1 SS VVVV

0b1 keeps all the 'playing card turned bits' at a consistent length.
SS is the suit value
VVVV is the card value
Here is how they form their bits
suits = ['Hearts','Diamonds','Spades','Clubs']
ranks = ['Ace','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King']

For this lets use the Jack of Diamonds
Step 1. Isolate the Suit and convert into bis. The 'suit bits' are equal to the index number of the suit in binary so Diamonds would be 0b01 or 0b1
Step 2. Shift your suit bits left 4 bits. 0b01 -> 0b010000
Step 3. Isolate the Rank and convert into bits. The 'rank bits' are equal to the index of the number of the suit in binary so Jack (11) would be 0b1011
Step 4. Add your rank bits into your suit bits. 0b010000 + 0b1011 = 0b011011
Step 5. Add your combined rank\suit bits to 0b10000000 to give a consistent length across all values. 0b011011 + 0b1000000 = 0b1011011
In a full deck of cards (All 52 cards no jokers) there are 741 characters in the card names.
A full deck of cards converted to bits is stored in 364 bits with 49% compression while still keeping 100% of the data.
I'm wondering if there's any more efficient way to store this data. I'm only in my 2nd year of Computer Programming, and I only have highschool level education, so I wouldn't know very much about this myself.
Here is their code http://repl.it/BA56

A: Another approach would be to give each card a number from 1 to 52
It could be interesting to define an order on colors such as the one defined in the Belote card game.
So :
0 = 1 of Clubs
1 = 2 of clubs
...
12 = king of club
13 = 1 of diamonds
...
and so on.
It is easy by having an order on colors to map any number from 1 to 52 to a card.
Finally you only need number from 1 to 52 to represent the whole card game. That is number from '000000' to '110001' that is only 6 bit by card.
In term of size it is equivalent to the system you use, and I think you cannot reduce it more than 6bit by card.

A: If you order the cards 2c,2d,2h,2s,3c,3d,3h,3s...Ac,Ad,Ah,As, then you can treat them simply as integers from 0 to 51, AND as bit-fields, because the suit becomes the two low-order bits. This also makes comparison by rank faster because you don't have to separate ranks to compare them (i.e., "rank > 10" just becomes "card > 35"). It also makes it simple to use the numbers in lookup tables. I have found this to be the most efficient general-purpose representation, and the one I use in my simulation library.

A: There are a couple ways you can reduce it further than six bits per card. First, enumerate your cards with a system like the other answers mentioned, like:
import itertools

suits = ['Hearts','Diamonds','Spades','Clubs']
ranks = ['Ace','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King']
cards = list(itertools.product(ranks, suits))

Any card is now representable as an index into the cards list, which requires enough bits to store a value in the range 0 to len(cards), calculable like:
from math import ceil, log2

def bits_for_index(sequence):
    return ceil(log2(len(sequence)))

So, bits_for_index(cards) returns 6.
But you can observe that for an ordering of the deck, after you choose each card, there is one less possibility for the next card (e.g., no shuffle will contain the Ace of Hearts twice). If you generate a shuffle by selecting a card from your ordering, deleting that card from your list of cards, then choosing the next from the remaining cards, the value of bits_for_index(cards) will eventually go down from 6 to 5, then 4, 3, 2, and 1.
The total number of bits required for this technique is calculated by sum(map(ceil, map(log2, range(52, 1, -1)))), which ends up being 249. You can print a shuffle and its binary representation with something like the following:
from random import randrange

def ordering(sequence):
    sequence = sequence[:]
    value = 0
    while sequence:
        index = randrange(len(sequence))
        print(sequence.pop(index))
        if sequence:
            value += index
            value <<= bits_for_index(sequence)
    return value

ordering_compressed = ordering(cards)
binary_representation = '{:0249b}'.format(ordering_compressed)
print('Compressed to', len(binary_representation), 'bits:', binary_representation)

To extract the ordering, you'd reverse the process, masking and shifting one bit, then two, then two, then three, and so on, until you have a list of indexes into the total cards list:
def extract_ordering(value, sequence):
    indexes = [0]
    while value:
        indexes.append(0)
        bits = bits_for_index(indexes)
        indexes[-1] = value & ((1 << bits) - 1)
        value >>= bits
    padded = [0] * (len(sequence) - len(indexes))
    indexes.extend(padded)
    sequence = sequence[:]
    for idx in reversed(indexes):
        print(sequence.pop(idx))

Also, you could compress a deck of cards further by enumerating all possible orderings and choosing one, which would require ceil(log2(factorial(len(cards)))) or 226 bits:
def ordering(sequence):
    return randrange(factorial(len(sequence)))

def extract_ordering(value, sequence):
    indexes = []
    digit = 1
    while value:
        indexes.append(value % digit)
        value //= digit
        digit += 1
    sequence = sequence[:]
    while indexes:
        print(sequence.pop(indexes.pop()))
    if sequence:
        print(*sequence, sep='\n')

This solution doesn't have quite so tidy a relationship between the bits in the ordering and each individual card, though. And it likely doesn't port quite so easily to languages without universal Big Integer support in their libraries.


text:
Q: Why when I run `head(df$date_time_hour)` I don't get the proper format that I know that the variable has (`%Y-%m-%d %H`) I have a data frame df with a column called datetime that summarises date and time. This column is in POSIXct format ("%Y:%m:%d %H:%M:%S). I created a new variable called Date_time_hour from this in which I only want the hour time (format "%Y:%m:%d %H"). My doubt is that when I run head(df$date_time_hour), I get the date but not the time in the console. Why is this? Am I doing something wrong?
The curious thing is that I don't get the commented problem with the below example.
The example:
df1<-data.frame(DateTime=c("2016-08-01 12:04:07","2016-08-01 12:06:07","2016-08-01 13:12:12","2016-08-01 14:04:07","2016-08-01 15:01:45","2016-08-01 15:34:07","2016-08-01 16:25:16","2016-08-01 16:29:16","2016-08-01 16:33:16","2016-08-01 16:54:16","2016-08-01 16:58:16","2016-08-01 17:13:16","2016-08-01 17:21:16","2016-08-01 17:23:42","2016-08-01 17:27:16","2016-08-01 17:28:16","2016-08-01 17:29:28","2016-08-01 17:42:08"),Var1=c( "V6", "V7", "V6", "V6", "V7", "V7", "V6", "V6", "V6", "V7", "V7", "V7", "V6", "V6", "V6", "V9", "V7", "V4" ),Var3=c(16 , 17, 19, 16, 17, 16, 17, 16, 16, 19, 17, 16, 16, 17, 17, 19, 16, 17))
df1$DateTime<- as.POSIXct(df1$DateTime, format= "%Y-%m-%d %H:%M:%S", tz= "UTC")
df1$Date_time_hour<- strptime(df1$DateTime, "%Y-%m-%d %H",tz= "UTC")
df1$Date_time_hour<- as.POSIXct(df1$Date_time_hour, format="%Y-%m-%d %H:%M:%S", tz="UTC")

df1
              DateTime Var1 Var3      Date_time_hour
1  2016-08-01 12:04:07   V6   16 2016-08-01 12:00:00
2  2016-08-01 12:06:07   V7   17 2016-08-01 12:00:00
3  2016-08-01 13:12:12   V6   19 2016-08-01 13:00:00
4  2016-08-01 14:04:07   V6   16 2016-08-01 14:00:00
5  2016-08-01 15:01:45   V7   17 2016-08-01 15:00:00
6  2016-08-01 15:34:07   V7   16 2016-08-01 15:00:00
7  2016-08-01 16:25:16   V6   17 2016-08-01 16:00:00
8  2016-08-01 16:29:16   V6   16 2016-08-01 16:00:00
9  2016-08-01 16:33:16   V6   16 2016-08-01 16:00:00
10 2016-08-01 16:54:16   V7   19 2016-08-01 16:00:00
11 2016-08-01 16:58:16   V7   17 2016-08-01 16:00:00
12 2016-08-01 17:13:16   V7   16 2016-08-01 17:00:00
13 2016-08-01 17:21:16   V6   16 2016-08-01 17:00:00
14 2016-08-01 17:23:42   V6   17 2016-08-01 17:00:00
15 2016-08-01 17:27:16   V6   17 2016-08-01 17:00:00
16 2016-08-01 17:28:16   V9   19 2016-08-01 17:00:00
17 2016-08-01 17:29:28   V7   16 2016-08-01 17:00:00
18 2016-08-01 17:42:08   V4   17 2016-08-01 17:00:00

For the above example, when I do head(df1$Date_time_hour), I get this:
> head(df1$Date_time_hour)
[1] "2016-08-01 12:00:00 UTC" "2016-08-01 12:00:00 UTC" "2016-08-01 13:00:00 UTC" "2016-08-01 14:00:00 UTC" "2016-08-01 15:00:00 UTC"
[6] "2016-08-01 15:00:00 UTC"

But with my own data data frame Owndata, when I do head(Owndata$Date_time_hour), I get this:
> head(Owndata$Date_time_hour)
[1] "2016-07-20 UTC" "2016-07-20 UTC" "2016-07-20 UTC" "2016-07-20 UTC" "2016-07-20 UTC" "2016-07-20 UTC"

However, I know that the format of Date_time_hour in my own data is correct since:
> str(Owndata$Date_time_hour)
 POSIXct[1:2841756], format: "2016-07-20 00:00:00" "2016-07-20 00:00:00" "2016-07-20 00:00:00" "2016-07-20 00:00:00" "2016-07-20 00:00:00" "2016-07-20 00:00:00"

Just another clue:
> dput(head(Owndata))
structure(list(Date_time_hour = structure(c(1468972800, 1468972800,
1468972800, 1468972800, 1468972800, 1468972800), class = c("POSIXct",
"POSIXt"), tzone = "UTC"), Date = structure(c(17002, 17002, 17002,
17002, 17002, 17002), class = "Date"), LN = c(0.407596172920513,
0.407596172920513, 0.407596172920513, 0.407596172920513, 0.407596172920513,
0.407596172920513)), .Names = c("Date_time_hour", "Date", "LN"
), row.names = c(NA, 6L), class = "data.frame")

My Owndata data frame has 2841756 rows. I don't know if that's the reason... Although it would strange...

A: I think that because every entry in df$Date_time_hour has time set to 0:00, the display is compacted to a date without time.
Adding one hour to each entry, the time will be displayed. Maybe you are subsetting the data, where time is set to 0:00 only, which explains this behavior.
require(lubridate)

require(lubridate)

df <- structure(list(Date_time_hour = structure(c(1468972800, 1468972800, 1468972800, 1468972800, 1468972800, 1468972800),
                                                class = c("POSIXct",  "POSIXt"), tzone = "UTC"),
                     Date = structure(c(17002, 17002, 17002,  17002, 17002, 17002), class = "Date")))

df$Date_time_hour + hours(1)

gives:
[1] "2016-07-20 01:00:00 UTC" "2016-07-20 01:00:00 UTC" "2016-07-20 01:00:00 UTC" "2016-07-20 01:00:00 UTC" "2016-07-20 01:00:00 UTC"
[6] "2016-07-20 01:00:00 UTC"


text:
Q: matplotlib axis auto scaling So I am trying to rewrite a MatLab script to work in python. The scaling of the plot doesn't happen automatically like in MatLab. Code below, so I know how to scale it my self but I just want it autoscaled like in Matlab. How to do this? The whole data set is much larger, but for now, I am only interested in one part.Whole data set
import pandas as pd
from matplotlib import pyplot as plt
filename1 = ("1_quartz_IR7_8s.csv")
dataquartz = pd.read_csv(filename1, header = None)
print(dataquartz.head())

filename2 = ("2_water_600s_IR7.csv")
datawater = pd.read_csv(filename2, header = None)
print(datawater.head())

norm = (datawater[1]-850)/dataquartz[1]
wavenumber = (1/datawater[0]-1/793.3)*10**7

plt.plot(wavenumber,norm)
plt.title("Python Script Test")
plt.xlabel("Wavenumber [1/cm]")
plt.ylabel("Intensity")
plt.xlim(1400,1850)
plt.grid("True")
plt.show()

Example plot


text:
Q: Safari will not redirect to querystring URL I have a site built with PHP that does a redirect after certain actions are performed.
header("Location: http://example.com/accountArea/?v=updated");

I then show a message based on the value of the query string value. In safari (and only in Safari) after the redirect, you will only see a blank page. I have tried using absolute URL and relative URL in my redirect, neither work.
I was unable to find a solution by searching the web so I hope someone here is familiar with this.

A: What do you see in Safari's location bar? What do you see when you view source of the blank page? What happens if you go to the URL directly by typing it in to the address bar rather than being redirected? Does any error message show up in apache's error_log?


text:
Q: How to call a jquery function from an action method in controller? I have a requirement to open a popup from an action method in controller. The action method is basically registering a user.
[HttpPost]
public ActionResult Register(RegisterModel model)
{
    if (ModelState.IsValid)
    {
        MembershipCreateStatus createStatus;
        Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

        if (createStatus == MembershipCreateStatus.Success)
        {
            FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
            //------------------------------------------
            //I need to call a jquery function from here
            //------------------------------------------
            return RedirectToAction("Index", "Home");
        }
        else
        {
            ModelState.AddModelError("", ErrorCodeToString(createStatus));
        }
    }

    return View(model);
}

The jquery function, present in the view, would just make a hidden DIV, visible, and set the opacity, etc, to represent a popup.
I need to call such a jquery function from the controller's action method shown above.

A: You cannot call client side script from the server. However, you can set indicators on the server side that the client side can look at to determine it's action.
I would set a bool in the model called ShowModalPopup and when createStatus == MembershipCreateStatus.Success, set that bool to true.
Now, on your view, write out the indicator:
@Html.HiddenFor(model => model.ShowModalPopup, new { id = "_showModalPopup" }) //add the id attribute for added performace

and in your jquery:
$(document).ready(function()
{
    if($('#_showModalPopup').val() == 'true')
    {
        //call your jquery modal popup method
    }
});

A: I'm not an expert at dotnet technology.
on my point of view, server side scripting and client side scripting shall be separate.
as javascript jquery is client side and dotnet is server side.
the server will handler request and process the server script then send the output to user browser, then only jquery function happen at user side.
basically for whatever need to be execute at client browser I will put them all in view (html).
 jquery and javascript they will probably need to run in html with script tag.
<script type="text/javascript">
    jQuery(function(){
        //call your function here
    });
</script>

I'm not sure if I helping or I don't understand the question. I am sorry


text:
Q: Sorting file into Groups Python The task is to: read tweets and separate them into to groups based on specific hours (Month-Day-Year-Hour). The tweets related to a specific hour will be stored in a separate file in a folder. With file name "Mon-Day-Year-Hour.txt".
I am new to python, only starting coding in it as of a couple of days ago for a class. As of right now I have the file that tweets came from loaded into a list, and have sorted the list based on time created. I have looked into the itertools.groupby() function, but I'm not sure how to implement it correctly or for my purpose.
Here's a bit of what I have so far:
for line in open("CrimeReport.txt", "r").readlines():
    tweet = json.loads(line)
    tweets.append(tweet)

Sorted tweets:
sorted_tweets = sorted(tweets, key=lambda item:datetime.datetime.strptime(item['created_at'],
                                    '%a %b %d %H:%M:%S +0000 %Y'))

I apologize for the poor formatting.

A: dic = {}
for key, value in groupby(v, lambda x: x%2):
    if key not in dic.keys():
        dic[key] = list(value)
    else:
        dic[key] += list(value)

groupby will get your data, and a function which will returns each data's id.
by iterating over groupby and adding data into a dictionary you have it completely grouped.
But if you have large data, dictionary may not be fast enough.


text:
Q: Place circuit figures side by side in tabularx environment My MWE,
\documentclass[a4paper,11pt]{book}
\usepackage{tabularx}
\usepackage{tikz}

\begin{document}
\begin{enumerate}

\newcommand{\OOO}[4]{%
\begin{tabularx}{\linewidth}{@{}X@{}l@{}}
\textbf{A)} #1 & \textbf{B)} #2 \\
\textbf{C)} #3 & \textbf{D)} #4 \\
\end{tabularx}}

{\item  Convert the current source into an equivalent voltage source\\
\OOO{\input{./ABC/SZ-1a.tex}}
{\input{./ABC/SZ-1b.tex}}
{\input{./ABC/SZ-1c.tex}}
{\input{./ABC/SZ-1d.tex}}}

\end{enumerate}
\end{document}

and displaying

Also
{\item Convert the current source into an equivalent voltage source...\\
\begin{tabular}{ll}
\textbf{A)} & \textbf{B)}\\
\input{./ABC/SZ-1a.tex}&\input{./ABC/SZ-1a.tex}\\
\multicolumn{2}{l}{} \\
\textbf{C)} & \textbf{D)}\\
\input{./ABC/SZ-1c.tex}&\input{./ABC/SZ-1d.tex}
\end{tabular}}

And displaying

Related to: Automatic right justify in table - multiple choice question
How is it shift down? Is there a solve?

A: If I understood it correctly, there is no special requirement for a tabularx or tabular solution.
The macro \OOO could be made with help of four minipages. I provide another way using tcolorbox and its raster library to set up the four parts:
\documentclass[a4paper,11pt]{book}
\usepackage{tikz}
\usepackage{lipsum}
\usepackage[skins,raster]{tcolorbox}

\begin{document}
\begin{enumerate}

\newcommand{\OOO}[4]{%
\begin{tcbitemize}[blanker,fonttitle=\bfseries,coltitle=black,
    raster valign=top,raster row skip=2mm,raster column skip=4mm]
  \tcbitem[title=A)] #1
  \tcbitem[title=B)] #2
  \tcbitem[title=C)] #3
  \tcbitem[title=D)] #4
\end{tcbitemize}}

\item Convert the current source into an equivalent voltage source
  \OOO{\includegraphics[width=\linewidth]{example-image-a}}
      {\small\lipsum[2]}
      {\small\lipsum[3]}
      {\includegraphics[width=\linewidth]{example-image-b}}

\end{enumerate}
\end{document}

The code above produces top align parts or cells. The following variation produces center aligned cells:
\documentclass[a4paper,11pt]{book}
\usepackage{tikz}
\usepackage{lipsum}
\usepackage[skins,raster]{tcolorbox}

\begin{document}
\begin{enumerate}

\newcommand{\OOO}[4]{%
\begin{tcbitemize}[blanker,fonttitle=\bfseries,coltitle=black,valign=center,
    raster equal height=rows,
    raster row skip=2mm,raster column skip=4mm]
  \tcbitem[title=A)] #1
  \tcbitem[title=B)] #2
  \tcbitem[title=C)] #3
  \tcbitem[title=D)] #4
\end{tcbitemize}}

\item Convert the current source into an equivalent voltage source
  \OOO{\includegraphics[width=\linewidth]{example-image-a}}
      {\small\lipsum[2]}
      {\small\lipsum[3]}
      {\includegraphics[width=\linewidth]{example-image-b}}

\end{enumerate}
\end{document}

Finally, there comes another variation which frames the four parts:
\documentclass[a4paper,11pt]{book}
\usepackage{tikz}
\usepackage{lipsum}
\usepackage[skins,raster]{tcolorbox}

\begin{document}
\begin{enumerate}

\newcommand{\OOO}[4]{%
\begin{tcbitemize}[enhanced,size=small,sharp corners,colback=white,
    colframe=black!20,colbacktitle=blue!10,
    fonttitle=\bfseries,coltitle=black,valign=center,
    raster equal height=rows,raster row skip=1mm,raster column skip=1mm]
  \tcbitem[title=A)] #1
  \tcbitem[title=B)] #2
  \tcbitem[title=C)] #3
  \tcbitem[title=D)] #4
\end{tcbitemize}}

\item Convert the current source into an equivalent voltage source
  \OOO{\includegraphics[width=\linewidth]{example-image-a}}
      {\small\lipsum[2]}
      {\small\lipsum[3]}
      {\includegraphics[width=\linewidth]{example-image-b}}

\end{enumerate}
\end{document}


text:
Q: Power consumption related to cache hit rate Studying computer science engineering, I came across this question:

We place an L0 cache in front of an L1 cache (so a fraction of the
  cache accesses are serviced by the L0 cache instead of the L1 cache), this creates an opportunity to save power. What should be the minimum hit rate in the L0 cache for this organization to save power? (Assume f is the hit rate in L0, and X and Y is the power consumed per access to the L0 and L1 cache, respectively.)

I think it has something to do with the power formula we saw:
\$P = \frac{1}{2} C V^2 a f + I_{LC} V + I_{SC} V\$
But I have honestly no idea how I can relate the cache hit ratio to this. Thank you!

A: I don't think you use that formula.
Just figure out the power savings from including the L0.
You have some situations (L0 hit - no L1 access; L0 miss - L1 access) compared to original (L1 access).
Since L0 is not free from a power standpoint, you have to have some balance point where adding the L0 in gives you a benefit.  As an extreme example if L0 missed 100% of the time, it would offer no additional power savings benefit and would actually increase the power by (X+Y)/Y %-age (as well as make the timing worse)


text:
Q: Every norm-decreasing algebra morphism $L_1(G)\to\mathcal{B}(E)$ comes from a group representation In section 8 of this paper http://arxiv.org/abs/math/0611833v3 the author proves the following:
If $E$ is a reflexive Banach space, $G$ a locally compact group and $\pi:L_1(G)\to\mathcal{B}(E)$ a norm-decreasing algebra morphism, then there exists a one-complemented subspace $F$ of $E$ and a group representation $\sigma:G\to\mathcal{B}(F)$ such that $\pi(f)$ restricted to $F$ is given by $\int f(s)\sigma(s)\,ds$.
I have two questions concerning the proof:
1) He takes an approximate identity $(e_{\alpha})$ in $L_1(G)$ of bound 1 and defines $\sigma:G\to\mathcal{B}(E)$ by
\begin{equation}
\langle\mu,\sigma(s)x\rangle=\lim_{\alpha}\langle\mu,\pi(s\cdot e_{\alpha})x\rangle\qquad (x\in E, \mu\in E^*)
\end{equation}
where $(s\cdot f)(t)=f(s^{-1}t)$.
Why does that limit exist for every $x\in E$?
2) Then there is a subspace $F$ such that, by restriction, $\sigma:G\to\mathcal{B}(F)$ becomes a group representation. Moreover, there exists a contractive projection $P:E\to F$ such that $P\pi(f)P=\pi(f)$ for all $f\in L_1(G)$.
Why does this contractive projection exist?
(He later concludes that $F=\{\pi(f)x\ :\ f\in L_1(G), x\in E\}$ thanks to the Cohen factorisation theorem)

A: 1) As Yemon said, just pass to a subnet (via compactness) where it converges.
2) Follow the suggestion in the paper and use Cohen Factorisation.  In the form I like, if $A$ is a Banach algebra with a bai and $E$ is a left Banach $A$-module, set $F$ to be the closed linear span of $\{a\cdot x:a\in A,x\in E\}$, then $F = \{ a\cdot x : a\in A,x\in E \}$ (no linear span or closure).
So, if $F = \{\pi(f)(x) : f\in L^1(G), x\in E\}$ then $F$ is equal to its own closed linear span, and is (clearly) equal to the collection of $x\in E$ such that $\pi(e_\alpha)x \rightarrow x$.  Taka said as much as this in his comment.
Now let $P$ be a weak$^*$-limit point of the net $\pi(e_\alpha)$ in $B(E)$.  Then $P(x)=x$ for $x\in F$.  Also $P\pi(f) = \pi(f) = \pi(f)P$ for all $g\in L^1(G)$, and so for $y=\pi(f)(x)\in F$ we have that $P(y)=y$.  Thus $P$ is a (contractive) projection onto $F$.
Now prove an identity like $(s\cdot f)g = s\cdot(fg)$ for $s\in G, f,g\in L^1(G)$.  It follows that $\sigma(s)\pi(f) = \pi(s\cdot f)$.  Hence also $\sigma(s)P=\sigma(s)$.  Similarly, $\sigma(s)\sigma(t) = \sigma(st)$.  So $\sigma$ restricts to a group representation on $F$.


text:
Q: CSS Flex One Large Div on the left and two small divs on the right I know I can easily achieve this kind of layout using the css float which is the current way I have the divs have the layout right now. But, I am trying to recode it and change it to flex alignment.
Here is my markup:

Post 1

Post 2

Post 3

And here is my CSS:
.the-post-inner {
    clear: both;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: flex-start;
    align-content: flex-start;
}

.the-post-inner a {
    margin-bottom: 4%;
}

.the-post-inner a .image {
      padding-bottom: 60%;
}

.the-post-inner a .content {
      padding: 20px;
}

.the-post-inner a .content h2 {
      margin: 0;
}

.the-post-inner a:first-child {
    flex: 0 0 60%;
    margin-right: 4%;
}

.the-post-inner a:not(:first-child) {
    margin-right: 0;
    flex: 0 0 36%;
    align-self: flex-start;

    overflow: hidden;
    float: left;
    display: block;
}

I tried several codes based on the answers in other posts but I can't seem to make this work.
Thanks in advance for the suggestions.
EDIT:
I was wondering if there is a way to achieve this without changing the current markup which is not to separate the left post in another div and the right posts in another container.
https://jsfiddle.net/pextb1of/

A: I just put some fix. maybe will help you.

.the-post-inner {
    clear: both;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: flex-start;
    align-content: flex-start;
    flex-direction: column;
    height: 100px;
    border: 1px solid #000;
}

a {
    /*border: 1px solid #000;*/
    margin-bottom: 4%;
    /*padding: 20px;*/
}

.the-post-inner {
    flex: 0 0 60%;
    margin-right: 4%;
}

.sec-inner {
    margin-right: 0;
    flex: 0 0 36%;
    align-self: flex-start;
    flex-direction: column;

    overflow: hidden;
    float: left;
    display: flex;
}

#the-posts{
  display: flex;
  flex-direction: row;
}

        Post 1

        Post 2
        Post 3


text:
Q: Experience with web crawlers on heroku Does anybody have experience coding web crawlers with gems such as anemone and deploying them to heroku for your own person use? Would such a continuously running programs violate any of heroku's TOA/TOS?

A: Not any more.
Heroku Acceptable Use Policy states in Prohibited Actions p.21 that crawler must

*

*identify itself via a unique User Agent

*obey robots.txt (including crawl-delay directive)

*from p.20 stems the requirement not use you crawler as an "open proxy"

NB! A free instance must not exceed 18 hours of work a day.

A: I don't have any experience with using web crawlers in Heroku (I would actually be interested in reading about that!). But here are my points:

*

*This is its prohibited content. Illegal activity is prohibited (duh) and since some sites "prohibit" web crawlers and screen scrapers (such as IMDb), that could be considered illegal. But let's ignore this for now.

*These are its prohibited actions. The following is prohibited:

data mining any web property (including Heroku) to find email addresses or other user account information;

*These are its usage limits:

*

*Network Bandwidth: 2TB/month - Soft

*Shared DB processing: Max 200msec per second CPU time - Soft

*Dyno RAM usage: 512MB - Hard

*Slug Size: 200MB - Hard

*Request Length: 30 seconds - Hard

*In its TOS, point 2.5., it's explained:

Repeated exceeding of the hard or soft usage limits may lead to termination of your account.

Emphasis is mine. Heroku gives each app 750 dyno hours. As long as you don't abuse Heroku's services and don't use it to gather personal info, I believe you're in the clear. I suggest:

*

*Somehow cap your web crawler. Just as you should limit the rate of API requests, you should have the common courtesy of limiting the speed of your crawler.

*Keep an eye on your dyno hours. You can do so here.


text:
Q: VSTO C# Word crashes after pasting bitmap to a footer Writing an add-in.
Trying to place an image in the footer of a Word document from an .resx file.
Since the InlineShapes.addPicture requires a path to a file, figured out I could use the clipboard instead to insert the picture (only temporarily), but Word keeps on crushing when Paste() is used.
it exits with code 0 (0x0).
Here is the code:
private void placeFooterNavigationOnce()
{
    Word.Range footerRange = Globals.ThisAddIn.Application.ActiveDocument.Sections[1].Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
    Clipboard.SetImage(Resource1.Brackets);
    footerRange.Select();
    Globals.ThisAddIn.Application.Selection.Paste();
}

Edit- Additional info:
inlineShapes.addPicture Does the same task without any errors.
Pasting the image in the body of the document works as well.

A: @MikeK, here is what I do in a VB.NET solution to get around trying to figure out why a Clipboard Copy/Paste of the bitmap wouldn't work for me. I'm sure you can adapt it to a C# solution.
            Dim img as Image, fName as String
            fName = "rClock32"
            img = My.Resources.ResourceManager.GetObject(fName)
            img.Save(ThisAddIn.LGPUserTempDir & fName & ".png")
            wApp.Selection.InlineShapes.AddPicture(ThisAddIn.LGPUserTempDir & fName & ".png")
            Kill(ThisAddIn.LGPUserTempDir & fName)
            img = Nothing


text:
Q: How to detect a component will be updated with react hooks? React hooks provides possibility to mimmic lifecycle method componentDidUpdate with useEffect without dependencies:
useEffect(() => {
   // componentDidUpdate
});

How can I detect if some prop GOING TO update with react hooks?
Need to execute some code right before some changes.

A: useEffect without a dependency will be called whenever the component re-renders. This is like a combination of componentDidMount and componentDidUpdate
However if you wish to track a specific prop change, you can add that to the dependency array of useEffect
useEffect(() => {
   // called on change of props.somename as well as initial render
}, [props.somename]);

Also check the below posts for more details on emulating lifecycle methods with useEffect as well as executing useEffect only on update
React hooks useEffect only on update?
ReactJS lifecycle method inside a function Component
P.S. You can add more than one value to the dependency array depending on your requirement

A: If you are trying to mimic the behaviour of componentWillReceiveProps you can easily put your logic inside the main body of the component:
function MyComponent(props) {
  // do stuff with props (it's like componentWillReceiveProps)
  return (...);
}

You don't need hooks for that.
Keep in mind that useEffect runs after your component was rendered with those props and not before.
newProps -> MyComponent is called -> DOM updated -> useEffect called


text:
Q: AttributeError: 'NoneType' object has no attribute 'hero_first' I keep getting this, have no idea how to make it work, I'm kinda new at python coding and this is giving me a headacke. Could not find any answer at all so please, just tell me what to do
'''
from tkinter import *
import random
import time
# Variables
# Player
class Player(object):
    health = random.randint(70,100)
    strength = random.randint(70,80)
    defence = random.randint(45,55)
    speed = random.randint(40,50)
    luck = random.randint(40,50)

    def __init__(self, arg):
        super(Player, self).__init__()
        self.arg = arg

# Beast
class Beast(object):
    health = random.randint(60,90)
    strength = random.randint(60,90)
    defence = random.randint(40,60)
    speed = random.randint(40,60)
    luck = random.randint(25,40)

    def __init__(self, arg):
        super(Beast, self).__init__()
        self.arg = arg

def begin():
    print("\nHero","          Beast"
"\nHealth:",    Player.health, "    Health:", Beast.health,
"\nStrength:",  Player.strength, "  Strength:",Beast.strength,
"\nDefence:",   Player.defence, "   Defence:", Beast.defence,
"\nSpeed:",     Player.speed, "     Speed:", Beast.speed,
"\nLuck:", Player.luck, "      Luck:", Beast.luck)
    print("\nBEGIN FIGHT")

def round_stat():
    print("Hero","          Beast",
    "\nHealth:", Player.health,"    Health:", Beast.health)

def who_move():
    hero_first = 1
    if Player.speed > Beast.speed:
        hero_first = 1
    elif Player.speed < Beast.speed:
        hero_first = 0
    else:
        if Player.luck > Beast.luck:
            hero_first = 1
        else:
            hero_first = 0

begin()

round_stat()

who_move()

if who_move().hero_first == 1:
    print("SUPPPPPPP")

'''

A: who_move() is function, not an object. So you can not access variable inside function.
So the quickest solution is set the hero_first as global:
def who_move():
    global hero_first
    hero_first = 1

who_move()

if hero_first == 1:
    print("SUPPPPPPP")

and then I got:
dubak@dubak-thinkpad:~/projects/$ python3 test.py
SUPPPPPPP

or rewrite the who_move function so it is returning directly value of hero_first. Something like this:
def who_move():
    hero_first = None

    if 2 > 1:
        hero_first = 1

    return hero_first

if who_move() == 1:
    print("SUPPPPPPP")

A: You cannot access the internal variables of a function using the . syntax. If you want that data to be accessible outside of the function, return it:
def who_move():
    if Player.speed > Beast.speed:
        return 1
    elif Player.speed < Beast.speed:
        return 0
    else:
        if Player.luck > Beast.luck:
            return 1
        else:
            return 0

Then, use it like:
if who_move() == 1

The other answer mentions global, but I would not use that here. Use of global should be limited, as it has a general tendency of making your code harder to maintain and understand.


text:
Q: Is there something like $this->db->matched_rows() in CodeIgniter? I want to update an entry in table or insert if not exist. I am using affected_rows() function but in case if data is unchanged it returns 0 and inserts a duplicate row.
I am using this code,
$datainsert = array(
    "vendor_id"   => $vendor_id,
    "c_date_time" => date('Y-m-d H:i:s')
);
$this->api_vendor_model->update_vendor_login_time($vendor_id, $datainsert);
if ($this->db->affected_rows() == 0) {
    $this->api_vendor_model->insert_vendor_login_time($datainsert);
}

but it does not work in case no rows are affected but an entry exists for vendor_id.
function update_vendor_login_time($vendor_id, $data) {
    $this->db->where('vendor_id', $vendor_id);
    $this->db->update('fa_vendor_login_time', $data);
    $this->error_check(__FUNCTION__);
}

A: Instead of controller you need to check $this->db->affected_rows()  in model file  and return TRUE or FALSE. To check duplicate entry your need to check it using select query
MODEL
 function update_vendor_login_time($vendor_id, $data) {
    $q = $this->db->select('id')// add your column nae here
                    ->from('fa_vendor_login_time')
                    ->where(array('vendor_id' => $vendor_id))->get();
    if ($q->num_rows() == 0) {
        $this->db->where('vendor_id', $vendor_id);
        $this->db->update('fa_vendor_login_time', $data);
        $this->error_check(__FUNCTION__);
        if ($this->db->affected_rows() > 0) {
            return TRUE;
        } else {
            return FALSE;
        }
    }else{
        return TRUE;
    }
}

CONTROLER
$insert = $this->api_vendor_model->update_vendor_login_time($vendor_id, $datainsert);
if (!$insert) {

    $this->api_vendor_model->insert_vendor_login_time($datainsert);
}

A: No, there's no such function.
affected_rows() works that way because that's how the database works - it won't return feedback for rows it didn't actually update. This is outside of the framework's control.


text:
Q: Multiple Api request using RxJava and Retrofit I fetch list of popular movies from the remote server using Retrofit and RxJava. Every movie has some info but I need more info about movie and I can do it with another request with passing movie_id and I receive more info about movie which id I passed. For exemple I need movie's genre but from first movie info request I have only ids of geners, if I will make another request using movie id I will get more info about movie and there is list of objects with genrs and their ids. How can I combine two requests in one object?
data of first request

data of second request where I pass movie_id and get genres

code from repository where I make request for movie with less info
class MoviesRepositoryImpl(
    private val schedulersIO: Scheduler,
    private val moviesApi: MoviesApi,
    private val moviesApiMapper: MoviesApiMapper
): MoviesRepository {

    override fun getPopularMovies(): Single<List<PopularMovieModel>> {
        return moviesApi.getPopularMovies()
            .subscribeOn(schedulersIO)
            .map { moviesApiMapper.mapPopularMoviesApiToModelList(it) }
    }
}

A: You can use flatMap operator with 2 parameters for this purposes:
getPopularMovies()
    .map {
        it[0] // get respective movie, in this case I just get a first movie in the list
    }.flatMap( {
        movie ->  api.getMovieDetails(movie.id) //request for movie details
            }, { movie, details ->  DetailedMovieModel(movie, description)}
       )

A: I found this solution
  private fun getPopularMovies(): Single<List<Result>> {
        return moviesApi.getPopularMovies()
            .map { it.results }

    }

    private fun getMovieDetailsList(): Single<List<MovieDetailsModelApi>> {

        return moviesApi.getPopularMovies().toObservable()
            .flatMapIterable {
                it.results
            }
            .flatMap {
                moviesApi.getMoviesDetails(it.id).toObservable()

            }
            .toList()
    }

   override fun getMoviesWithDetails() :Single<List<PopularMovieWithDetailsModel>>{
        return Single.zip(getPopularMovies(),getMovieDetailsList()) { movieList, detailsList ->
            moviesApiMapper.mapMovieDetailsAndMoviesToModelList(detailsList, movieList)
        }
            .subscribeOn(schedulersIO)

    }