text:
Q: I accidentally deleted crucial videos from my iPhone DCIM folder on my desktop I copied the files onto my desktop and then accidentally clicked 'delete' on my keyboard. It deleted the selected videos. I then did ctrl+z which deleted the copied files that I placed on my desktop. Now I have no access to any of the files. Is there any way I can recover the files I deleted?
EDIT: I cannot use the programs/solutions stated in the possible duplicate question because it does not detect my iPhone as a drive.

A: You'd better stop using the your iphone, this will prevent new files to be written to the device and hence increase chance of DCIM folder data recovery.
Some suggestion for you:
If you deleting videos from iPhone Using a Mac
This works in all versions of Mac OS X:

*

*Connect the iPhone to the computer via USB;

*Launch videos from the /Applications/ folder;

*Hit Command+A to Select All videos, then with all images selected
click the red () button to delete all videos.

*Confirm deletion when asked and be prepared to wait.

If you delete All Photos from iPhone Using Windows PC
This should work in all versions of Windows:

*

*Connect the iPhone to the computer via USB;

*Open 'My Computer' and choose "Apple iPhone";

*Open to folders "Internal Storage" and then open "DCIM", contained
within will be a folder containing all videos on the iPhone;

*From the folder containing the videos, select all, then delete
Removing videos from the iPhone.

Select a recovery suite.
The software mentioned is EaseUS Data Recovery Wizard and Recuva for Windows, which are both free options.


text:
Q: Cant send a post request to my api with flutter I am trying to make a post request to my api to create a new user. My api works and I tried everything that I could find. The output is: Unhandled Exception: Bad state: Insecure HTTP is not allowed by platform: http://10.0.2.2:5000/api/register
I am using an android emulator I tried to use on my android phone it didn't work...

A: If you want to allow HTTP request (it's by default disabled), you have to add this code in application tag in android manifest file:
<application android:usesCleartextTraffic="true"/>

and for iOS view info.plist as source code and add this code:
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does setValue:forKey: fail on a 32-bit system but not 64-bit? I recently submitted a bug report to Apple about this, but I thought I would ask the question anyways in case I'm missing something obvious. In Objective-C, the following call works fine on a 64-bit system but throws an NSInvalidArgumentException on a 32-bit system:
[self setValue:@"true" forKey:@"flag"];

The "flag" property is a BOOL:
@property BOOL flag;

Further, the call works fine in Swift/32-bit, where the property is a Bool:
var flag: Bool = false

Similarly, this call works fine in Swift on a 64-bit system but throws NSInvalidArgumentException on the 32-bit system ("index" is an Int):
setValue("2", forKey: "index")

Yet it works fine in Objective-C/32-bit, where the property is an NSInteger.
I would have expected these calls to work correctly regardless of language or processor architecture. Does anyone have any insight into why they might not?

A: The answer is there in the comments if you combine them all...
setValue:forKey: does not require an NSNumber/NSValue for primitive-typed properties, but you would normally pass one.
The observed issued is not down to 64-bit vs. 32-bit either, the example code can fail on 64-bit systems as well.
It is all down to the nature of BOOL and whether it is a char or a bool,as a comment suggests - and that depends on a number of things (from Xcode 6.4 running on 10.10.5):
/// Type to represent a boolean value.
#if !defined(OBJC_HIDE_64) && TARGET_OS_IPHONE && __LP64__
typedef bool BOOL;
#else
typedef signed char BOOL;
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C"
// even if -funsigned-char is used.
#endif

setValue:forKey when setting a primitive typed property of <type> calls - <type>Value on whatever object it is passed.
If BOOL is a char it calls - charValue, and NSString has no such method - so fail.
If BOOL is bool it calls - boolValue, and NSString has that so all is good.
Simple fix:
@property bool flag;

and that should work everywhere and have the added bonus that flag will always be true/false, YES/NO, 1/0 and not one of the other 254 possibilities that char can be.
Just think how different things would be if the designers of C didn't skimp and actually included a real boolean type from the start...

A: As @CRD mention above, BOOL is a typedef of char on 32bit devices, and NSString has no charValue method, so we can add a simple NSString category to fix it, like this.
#import "NSString+DCCharValue.h"

@implementation NSString (DCCharValue)

#if !defined(OBJC_HIDE_64) && TARGET_OS_IPHONE && __LP64__
#else
- (BOOL)charValue {
    return [self boolValue];
}
#endif

@end


text:
Q: Split image into smaller chunks,shuffle chunks and then save into my sd card in Android I am working on a task in which i am split the image into smaller chunks and i have done it successfully with the help of this link,now my point is and i want to shuffle that chunks and then save into my sd card as it is,any help will be much appreciated Thanks in advance..

*

*want to shuffle the chunks

*after shuffling the chunks save that image as it is into my sd card

This is the image:

A: Farhan,
In ChunkedImageActivity.java,
Use Collections.shuffle(imageChunks); after
ArrayList imageChunks = getIntent().getParcelableArrayListExtra("image chunks");
You will get the shuffled images.
To store these images in sdcard, use FileOutputStream.
Follow this link http://looksok.wordpress.com/2013/07/13/android-tutorial-save-bitmap-image-on-android-sd-card/


text:
Q: For which $m \in \mathbb N$ is the ideal $(m,x^2+y^2)$ prime in $\mathbb Z[x,y]$?
Let $m \in \mathbb N$. Find a necessary and sufficient condition for
  $m$ such that the ideal $(m,x^2+y^2)$ is prime in $\mathbb Z[x,y]$.

I have to find for which $m$ the quotient ring is an integral domain. I do not know how to use the isomorphism theorem: is it ture that
$$
\mathbb Z[x,y] /(m,x^2+y^2) \cong (\mathbb Z_m[x])[y]/(x^2+y^2)?
$$
What should we do? Thanks in advance.

A: Clearly $m = p$ has to be a prime, otherwise its factors are zero divisors.
Also, $\mathbb{Z}[x,y]/(p,x^2+y^2) \cong (\mathbb{Z}_p[x])[y] / (x^2 + y^2)$ is isomorphic by the third isomorphism theorem.
With $\mathbb{Z}_p$ being a field, $\mathbb{Z}_p[x]$ is a PID and so $(x^2 + y^2)$ is a prime ideal in $\mathbb{Z}_p[x,y]$ if and only if $f(y) := x^2 + y^2$ is irreducible over $\mathbb{Z}_p[x]$ (by Gauss's lemma).
$f(y)$ is irreducible if and only if it has no zeros (being a quadratic polynomial), and any zero would have to be of the form $\sqrt{-1}x$; so $f$ is irred. if and only if $-1$ is not a square ($\bmod p$).
By quadratic reciprocity (or rather its supplement) this is if and only if $p \equiv 3 (\bmod 4)$.


text:
Q: can you produce BEQL MIPS instruction with C code? So I have this code snippet in C
int unit_test_case08(int a, int b)
{
    int success = 1336;

    if(a != b)
    {
      success = 1337;
    }
    else
    {
      success = -1;
    }

    return success;
}

Which translates in MIPS to
unit_test_case08:
        addiu   $sp,$sp,-24
        sw      $fp,20($sp)
        move    $fp,$sp
        sw      $4,24($fp)
        sw      $5,28($fp)
        sw      $6,32($fp)
        li      $2,1336           # 0x538
        sw      $2,8($fp)
        lw      $3,24($fp)
        lw      $2,28($fp)
        nop
        beq     $3,$2,$L2
        nop

        li      $2,1337           # 0x539
        sw      $2,8($fp)
        b       $L3
        nop

$L2:
        li      $2,-1                 # 0xffffffffffffffff
        sw      $2,8($fp)
$L3:
        lw      $2,8($fp)
        move    $sp,$fp
        lw      $fp,20($sp)
        addiu   $sp,$sp,24
        jr      $31
        nop

But for my question, im trying to create some test cases for my emulator, but am finding it hard to generate some code in C that will get me BEQL instead of BEQ?
beq     $3,$2,$L2

This question extends to most of the "Likelys" if possible.
I am a very new to MIPS.
I would like to learn how to code a test case in C that would translate to BEQL instead of BEQ.


text:
Q: Unable to trigger change event of a dropdown element in document ready In $(document).ready(), I am setting a particular dropdown's first element to be selected. I also need to trigger the change function on the dropdown as if the option were manually selected. If the change is triggered, the showTestsByPanel function is called and shows appropriate data associated with the selected dropdown option.
I am doing the following, but it doesn't help trigger the change function:
$(document).ready(function () {
    $("#lbpanel option:first-child").attr('selected', 'selected');
    $('#lbpanel').trigger('change'); // <-- this is not triggering the change

    $('#lbpanel').change(function () {
        var $this = $(this);
        var parentId = $("#lbpanel").find("option:selected").val();
        $("#selectedTests tr").each(function () {
            showTestsByPanel(parentId, $(this));
        });
    });
});

I also tried $('#lbpanel').change() instead, but that did not work as well.
If it helps:

*

*this whole thing is inside a modal dialog.

*this is actually a listbox where allowmultiple is set to false.

What am I doing wrong?

A: You are trying to trigger change event before handler creation. That's why no effect.
So call the change() after registering change event handler
$(document).ready(function () {
    $("#lbpanel option:first-child").attr('selected', true);
    $('#lbpanel').change(function () {
        var $this = $(this);
        var parentId = $("#lbpanel").find("option:selected").val();
        $("#selectedTests tr").each(function () {
            showTestsByPanel(parentId, $(this));
        });
    }).change(); //added change here
});

A: You need to trigger the change event after the trigger handlers are registered, when the event is triggered it will invoke only those handlers which are already registered.
$(document).ready(function () {
    $("#lbpanel option:first-child").attr('selected', 'selected');

    $('#lbpanel').change(function () {
        var $this = $(this);
        var parentId = $("#lbpanel").find("option:selected").val();
        $("#selectedTests tr").each(function () {
            showTestsByPanel(parentId, $(this));
        });
    }).trigger('change'); // need to trigger the event after the handler is added
});


text:
Q: Reset SelectableLabel in kivy ScreenTest is a screen with:
- A view with selectable labels
- A Label that changes dependant on the selected label
- A reset button
The reset button is supposed to reset the selection made in the view, but I do not know how to the selected SelectableLabel and then set its "is_selected" to False. There is no id or class I could access to change this parameter
What I need is that, through clicking the reset button, nothing in the view is selected and therefore no text is shown in the Label (or the text is reset to "" as text_selected is empty).
from kivy.app import App
from kivy.lang import Builder
from kivy.properties import BooleanProperty
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.label import Label
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.screenmanager import ScreenManager, Screen

Builder.load_string("""

<ScreenTest>:
    BoxLayout:
        TestView:
            id: test_view

        Label:
            id: text_lbl
            text: "" if not test_view.text_selected else test_view.text_selected

        Button:
            id: reset_btn
            on_press: print("Wow")

<TestView>:
    viewclass: 'SelectableLabel'
    text_selected: ''
    name_selected: ''

    SelectableRecycleBoxLayout:
        id: culture_sub_view_layout
        orientation: 'vertical'
        default_size: None, dp(32)
        default_size_hint: .6, None
        size_hint: 1, .9
        multiselect: False
        touch_multiselect: False

<SelectableLabel>:
    # Draw a background to indicate selection
    canvas.before:
        Color:
            rgba: (.05, 0.5, .9, .8) if self.selected else (.5, .5, .5, 1)
        Rectangle:
            pos: self.pos
            size: self.size
""")

class TestView(RecycleView):
    def __init__(self, **kwargs):
        super(TestView, self).__init__(**kwargs)
        self.data =  [
            {"text": "Test1", "description": "Test1.text"},
            {"text": "Test2", "description": "Test2.text"},
            {"text": "Test3", "description": "Test3.text"}
        ]

class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,
                                 RecycleBoxLayout):
    pass

class SelectableLabel(RecycleDataViewBehavior, Label):
    index = None
    selected = BooleanProperty(False)
    selectable = BooleanProperty(True)

    def refresh_view_attrs(self, rv, index, data):
        self.index = index
        return super(SelectableLabel, self).refresh_view_attrs(
            rv, index, data)

    def on_touch_down(self, touch):
        if super(SelectableLabel, self).on_touch_down(touch):
            return True
        if self.collide_point(*touch.pos) and self.selectable:
            return self.parent.select_with_touch(self.index, touch)

    def apply_selection(self, rv, index, is_selected):
        self.selected = is_selected
        if is_selected:
            print("selection changed to {0}".format(rv.data[index]))
            rv.name_selected = rv.data[index]['text']
            rv.text_selected = rv.data[index]['description']
        else:
            print("selection removed for {0}".format(rv.data[index]))

class ScreenTest(Screen):
    pass

sm = ScreenManager()
sm.add_widget(ScreenTest(name='menu'))

class TestApp(App):
    def build(self):
        return sm

test_app = TestApp()
test_app.run()

Thanks!

A: Quick solution
I believe the simplest method would be to iterate over elements within the recycle box, deselect them if they were selected and set the text to "". Consider a following function declared within your TestView class:
def remove_selection(self):
    # Remove text
    self.parent.children[1].text = ""

    # Remove selection
    for child in self.children[0].children:
        if child.selected:
            child.selected = False

Naturally, you have to call it when the button is pressed, you can change your layout to:
Button:
    id: reset_btn
    on_press: test_view.remove_selection()

Slightly better way
Calls to children and parents can get quite messy in more complex layouts, so I'd like to suggest a cleaner way to solve your problem. Since you only handle 1 selected item at a time, I think the best approach would be to store the item itself within your program and retrieve information from it when needed. Precisely, instead of storing name_selected and text_selected in your test_view, you could simply store the selected item. To do that, a number of changes have to be introduced:

*

*Import ObjectProperty and StringProperty:
from kivy.properties import BooleanProperty, ObjectProperty, StringProperty

*Add a selected attribute to your TestView class, allowing None will help to check if anything is selected at all:
class TestView(RecycleView):
    selected = ObjectProperty(None, allownone=True)

*Edit remove_selection method I've mentioned above:
def remove_selection(self):
    # Remove selection
    if self.selected is not None:
        self.selected.selected = False
        self.selected = None

*Add text_selected and name_selected properties to the SelectableLabel class:
class SelectableLabel(RecycleDataViewBehavior, Label):
    index = None
    selected = BooleanProperty(False)
    selectable = BooleanProperty(True)
    text_selected = StringProperty()
    name_selected = StringProperty()

*Edit apply_selection method:
def apply_selection(self, rv, index, is_selected):
    self.selected = is_selected
    if is_selected:
        print("selection changed to {0}".format(rv.data[index]))
        # Store selected text and name inside the label
        self.name_selected = rv.data[index]['text']
        self.text_selected = rv.data[index]['description']
        # Remember the selection
        rv.selected = self
    else:
        print("selection removed for {0}".format(rv.data[index]))

*Change the text displayed in your text_lbl:
Label:
    id: text_lbl
    text: "" if test_view.selected is None else test_view.selected.text_selected

*Remove not needed properties (text_selected, name_selected) from <TestView>:
<TestView>:
    viewclass: 'SelectableLabel'


text:
Q: Questions to expect in an interview for a Junior Magento Developer Position Firstly I would like to say that I hope I am not posting in the wrong place with this question and if I am please advice me of where (if anywhere in the stackexchange world is appropriate) I should post it.
I have a couple of interviews coming up for junior Magento developer positions. I have some Magento development experience but I never did an interview for these jobs so I am not sure what to expect.
I would appreciate all comments and answers and I think this post could potentially be very helpful to other junior developers trying to break into magento

A: The first question you would probably expect is something along the lines of:
Here's a default installation, now remove the "Back to School" block from the home page using local.xml.
You mights also find something such as:
Find out why the default checkout process is not performing the way it should. (hint, check for javascript errors in console).
After installing a third-party module that modifies how product images are displayed, the product view page is missing another feature generated by a separate third-party module. What is the first step to debug this? (hint: 'depends').
The customer would like a space on the home page where they can easily modify content without having to deal with much 'code'. How would you implement this?
I personally saw all of these questions during an interview.
And then, of course, expect some questions regarding common Magento mistakes during development (clear cache, reindex, base_url mistakes, etc). If you nail everything, expect some more difficult subjects (EAV, class rewrites, updating a block via AJAX).
Depending on who you're interviewing, it might be enough to just have a good understanding of a few basic areas of Magento (layout XML, working with templates) since the first months of your employment may likely involve fixing random frontend issues on random sites. If you're relatively new to Magento and find yourself hired as a jr developer, expect to do a lot of on-the-job learning.

A: I was thinking of posting the same questions! I created a list based on the FED study guide, I have shared it as a Google Doc, if anyone wants to comment I would be interested in hearing what you have to say
https://docs.google.com/document/d/19iMKDOFBwYpq6wDQBknT8u5kDYFh7DssdjBDPTTsHwA/edit?usp=sharing

A: I'm not sure that exactly what questions and tasks will be given for juniors, but you can see these sources to right orientation and figure out interview:

*

*https://stackoverflow.com/questions/16289832/preparing-for-magento-front-end-certification

*Studying to become a Magento Certified Developer

*http://blog.belvg.com/tag/study-guide

*https://www.acmecollinsschool.com/basic-computer-course.html

*http://magentoquiz.com/magento-certification/magento-exam-sample-questions/

A: When I'm interviewing candidates, and in particular junior candidates, I first assess whether they're going to be good developers. Nevermind Magento.
So you would hear a lot of generic, non-Magento, questions from me up front. Here are just a few:

*

*Explain the difference between a map, a hash, an array, a collection, and a list.

*Explain what you think "inheritance" means, and give me an example that doesn't involve cars or family members.

*Name 3 types of security vulnerabilities that are commonly introduced by unfiltered user input.

*Explain what a prepared statement is and what it does.

*What is your favorite new feature in PHP 5.5?

*Name at least 3 major PHP frameworks.

*What is the difference between a function declaration and a function expression?

Some non-technical questions:

*

*Tell me the last time you made a mistake that cost a company or client money, and:

*What did you learn from your mistake?

*What do you do to keep current on technologies?

*What are you learning in your off-time?

Then I might ask them to do a code review with some of their work on Github or something they've submitted; we might do some whiteboard exercises like Fizzbuzz, maybe a selection from Project Euler... something to that effect. I'm just trying to mix it up here and see how they deal with problems they may not have encountered.
If I'm satisfied and I know that the candidate has Magento experience I might ask more specific Magento questions:

*

*How does Magento MVC differ from classical MVC (or Zend Framework MVC)?

*Name 3 types of Magento Models

*Describe or give me an example of Magento code pools and/or theme fallback

*When is it okay to make a core modification? (answer: NEVER.)

*List at least 3 techniques to override default/core functionality.

At this point I may ask some really hard questions or have them sketch out something for me - maybe the checkout flow of Magento. I may have them describe all of the subfolders in a Magento Extension. I might ask them what abstract models to extend for desired functionality.
I hope this helps - the hire process is difficult for both parties at the table. In my first round of hiring my first time out I phone screened over 75 applicants, sifted through 500+ resume submissions and whittled it down to 2 or 3 in-person interviews. None of them worked out - so, in my case, when you're sitting across the table from me I'm rooting for you! I want you to make it! I want the torturous process of the hiring phase to end so we can do what we do best - build awesome products.
The trick is to keep it light and make it a useful and at the least an educational experience for the candidate.

A: Based on the discussion I had with Magento partners (note: i have not interviewed developers myself), below are couple tips:
1) Don't look for Magento developers. Find good OO PHP (or Java, I've heard success stories of getting Java devs do Magento) developers and train them. We also have some people in house that moved from Java to Magento and they don't have the bad habits of typical PHP devs.
2) Never use an external hiring company - they won't find anyone and they do not know what they are doing (ie they chase me because i work for Magento and i was a developer long time ago - but i'm not a Magento developer)
3) Not sure what is your role/company. If you want to do development, yeah look for people. However if you are a merchant or need to do just one project, consider going with some experienced partner instead.
4) Get @benmarks to answer - he is running internal training for new hires at BlueAcorn and hopefully can share some good insights

A: Here is collection of question and answer for interview
http://magentotutorialbeginners.blogspot.in/2014/03/magento-interview-questions-and-answers.html

A: Below are the collection of magento interview question :

*

*How to get CMS page id in Magento?

*Difference between Up-sell, cross sell and related products?

*Can a custom module have more than one namespace?

*Difference between Controller and controllers module?

*Request Flow

*Magento : File permissions needs to be set

*Where is the relation between configurable product and it's simple product stored in database?

*What are the commonly used block types? What is the special in core/text_list block type.

*Explain different types of sessions in Magento (e.g. customer/session, checkout/session, core/session) and the reason why you store data in different session types?

*Is it mandatory to give Namespace while creating custom module in Magento?


text:
Q: Game maker physics: using different restitutions in one object I try to make a game in wich the player makes atoms. I'm really far in making a good looking and working game.
But now I want to make the atoms have different properties for different phases (solid, liquid, gas) I found that I can't use Phy_restitution because it doesn't exist, so I tried making three objects (solid, liquid and gas) and give them their own properties.
But this didn't work. The create event checks in wich state the atom should be and creates that state, but this gives me a error.
How can I make three phases with different restitution of this atom?
------create event------ obj_h_parent
temp = global.temp
if temp < 14 instance_create(x,y,obj_h_solid) instance_destroy()
if temp > 14 and temp < 20 instance_create(x,y,obj_h_liquid) instance_destroy()
if temp > 20 instance_create(x,y,obj_h_gas) instance_destroy()

the error that I got was :
FATAL ERROR in
action number 1
of Create Event
for object obj_h_parent:
PerformEvent recursion depth failure - check for infinite loops, check objects for parenting
 at gml_Object_obj_h_parent_CreateEvent_1 (line 4) - if temp > 20 instance_create(x,y,obj_h_gas) instance_destroy()
I today tried to do it another way by making three objects and letting them check the temperature when they are created by:
    temp = global.temp
    if temp < 14 instance_create(x,y,obj_h_s) instance_destroy()
    if temp > 14 and temp < 20 instance_create(x,y,obj_h_l) instance_destroy()
    if temp > 20 instance_create(x,y,obj_h_g) instance_destroy()
But when I runned it game maker gave the same error as before. And I have deleted the parent.

A: Looking at your error message, I assume obj_parent is the parent of your liquid, solid and gas objects. I also assume that in the create event of the children, you use the event_inherited() function, or that you left this event blank, leading to the same result.
So when you create your obj_parent, the create event immediately creates a children, that runs the same creation code, meaning that it also creates an other instance before destroying himself.  Then this new instance creates an other, that creates an other, that creates an other, etc. This is where your infinite loop is.
Before creating & destroying, you should first check if your instance isn't already in the correct state. Or you could use the instance_change() function and tell it not to run the creation code again. https://docs.yoyogames.com/source/dadiospice/002_reference/objects%20and%20instances/instances/instance%20functions/instance_change.html
For example :
temp = global.temp
if (temp < 14) instance_change(obj_h_solid, false);
else if (temp > 14 && temp < 20) instance_change(obj_h_liquid, false);
else if (temp > 20) instance_change(obj_h_gas, false);


text:
Q: unable to execute server.js program using express framework on node.js While trying to execute server.js program I am getting the following error:
var app = express();
Type error: object is not a function
   at object.<anonymous>

even tried re installing and changing the version of express to
npm install
npm uninstall express
npm install express@2.5.9

but it resulted in new error
fqdn = ~req.url.indexof(' ://')

I use windows and i am working on node.js version 0.8.4.

A: If you're using Express < 3.0, the return value of require('express'); is not a function; you'll need to create a server the old way.
Express 2.x
var express = require('express');
var server = express.createServer();

Express 3.x
var http = require('http');
var express = require('express');
var app = express();
var server = http.createServer(app);

A: What does
> require('express').version;
'3.0.0rc2'

return?
As you can see it does return 3.0.0rc2? Does yours really return 2.5.9. if it does you use like Brandon said 2.x section. If it returns 3.x you use his 3.x section.


text:
Q: ViewPager unable to load images lazily with Picasso I have a FragmentActivity in the first tab of a TabHost, and the FragmentActivity itself holds a ViewPager.
The ViewPager's setAdapter() method sets a FragmentPagerAdapter with a set of Fragments. The goal is to have swipeable images in the first pane of the TabHost.
To test it, I was loading a bunch of images that I had kept locally in the project's drawable directory. Everything worked beautifully.
After having tested this initial setup, I'm downloading a bunch of image URLs' off a REST web service. I want these images to load lazily in the ViewPager, and I tried calling Picasso's load() method in three places:

*

*The onCreateView() method of the ViewPager's Fragments (the same place where I was earlier loading images from the local drawable directory).
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {

    View myFragmentView = inflater.inflate(R.layout.layout_fragment, container, false);

    ImageView imageView = (ImageView)getView().findViewById(R.id.fragment_image);
    String url = getArguments().getString(IMAGE_RESOURCE_URL);
    Context context = getActivity();
    Picasso.with(context).load(url).fit().into(imageView);

    return myFragmentView;
}

*The onViewCreated() method of the ViewPager's Fragments.
@Override
public void onViewCreated(View view, Bundle savedInstanceState){

    Context context = getActivity();
    String url = getArguments().getString(IMAGE_RESOURCE_URL);
    ImageView imageView = (ImageView)view.findViewById(R.id.fragment_image);
    Picasso.with(context).load(url).fit().into(imageView);

}

*The onInstantiateItem() method of the FragmentPagerAdapter.
@Override
public Object instantiateItem(ViewGroup container, int position) {

    View v = inflater.inflate(R.layout.layout_fragment, container, false);
    Context context = Tab1Activity.this;
    String url = getItem(position).getArguments().getString("IMAGE_RESOURCE_URL");
    ImageView imageView = (ImageView)v.findViewById(R.id.fragment_image);
    Picasso.with(context).load(url).fit().into(imageView);
    return v;
}

None of these methods worked. I know that its not a problem with Picasso because the other day I tried using Picasso in a ListView and it worked like a charm. What am I doing wrong ?

A: Your first approach should work fine... if you implement it correctly. I would expect your code to crash with a NullPointerException.
Replace:
ImageView imageView = (ImageView)getView().findViewById(R.id.fragment_image);

with:
ImageView imageView = (ImageView)myFragmentView.findViewById(R.id.fragment_image);

A: Your lazy loader should work in the context of the
Fragment.createView()
where  the Fragment is one of  a collection being paged by the ViewPager and the FragmentpagerAdapter
That is your option one.
I use another lazyloader that manages local memcache and local filesys cache for the bitmaps needed to load the images. at the time of the "OnCreateView()" it will go to the network to get the URL for the loader if the bitmap is not already cached.


text:
Q: JQuery can't load file from computer, error 0 I am trying to run the following script:
<button id="loadNoTextFile">Try</button>

However, instead of the supposed Error 404, I get Error 0 (this is a sample code from thise website: https://www.yogihosting.com/jquery-load/ )
I have also tried to load a file that does exist on my computer (right next to this html file), but it will not load it. Can somebody please help me solve this?
edit: Opening web console, I got the following error message in the Debugger tab:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///D:/Games/WORK/Agrisol/website/no-file.txt. (Reason: CORS request not http).
edit2: For further clarification, my end goal is to load html code into my website when a button is clicked. This website will be hosted on a VPS, not on my personal computer.


text:
Q: How do I set the default contacts container for my iOS app to the contacts container that is saved in iCloud? I am writing an iOS app using Swift and Xcode 13.1. I am using the Contacts Framework, and I read that each app has a default contacts container, and the default container in an app can be different than the default container in another app, and there is not a default container for the entire device.
What determines which is the default container for the app made by an Xcode project? I didn't set the default container for my app and somehow the contacts container for a Google account became the default contacts container for my app. How do I use code to set the default contacts container for my app?
How do I find out which is the default container of Apple's Contacts app that comes with iOS? I would like to set my app's default contacts container to the same default container of Apple's Contacts app, if that is the contacts container that is saved on iCloud. If not, I would like to set my app's default contacts container to the contacts container that is saved in iCloud. I assume that only one contacts container is saved on iCloud.

A: The user can specify the default contact container for new contacts in settings.  Your app can access the identifier of this container using defaultContainerIdentifier.
If you want to allow the user to specify a different container for new contacts created by your app, then you need to code that yourself.
You need to provide a view that displays the list of contact containers resulting from a call to containers(matching:nil).  Once the user selects a container, store its identifier in your apps preferences and use that container identifier when you create new contacts.
All you can know about a container is its identifier, its name and its type (Exchange, CalDAV or local).


text:
Q: Multiple background images in one div, one image after the other Lets say that I have 2 images, one is 1px*700px and the second is 1px*800px. I want to put those images as a background to one div, so that the div has 1500px height.
Is that possible with CSS3?
div{
    background: url(first_image.jpg) repeat-x, url(second_image.jpg) repeat-x;
    /* ... */
}

I could "join" those images in Photoshop, but I'm wondering if there is a CSS3 solution.
My problem: currently I have two divs and each has one background-image so when put together it looks good. My problem is that I have an element that needs to be right in the place where those two divs "join", and when I place that element there - it breaks the layout. I could play with position: absolute, but I'd prefer to avoid that.

A: With the height of the div equal to the height of both background images, you can use bottom to move the second background image underneath the first.
Example

div {
  background: url(http://www.placehold.it/5X100) repeat-x,
  url(http://www.placehold.it/5X100/FF0000) bottom repeat-x;
  height: 200px;
}


text:
Q: What am I getting wrong in my Apache configuration? I'm running an AWS setup that currently consists of an ELB pointing to a single EC2 instance. The instance is running Ubuntu 12.04.2 and Apache 2.22.2. I've setup several subdomains on the server in the past. I'm trying to set another one up today, but I'm beating my head against the wall trying to figure out what I missed. I'm sure it's some little step that I've overlooked or gotten not-quite-right.
My DNS records are setup using Route 53. I logged in to the AWS console and added a new CNAME record for my server. We'll call it samael.example.com. It looks like this:
samael.example.com. 3600    IN  CNAME   web-pool-xxxxxxxxxx.us-east-1.elb.amazonaws.com.

That seems to be working just fine, as pointing my browser to sameael.example.com brings up the default VirtualHost.
So, all I have left to do now is create another VirtualHost config file, right?
mkdir /http/www/samael.example.com
touch /httpd/www/samael.example.com/index.html
cd /etc/apache2/sites-available
sudo cp dav.example.com samael.example.com
sudo sed -i 's/dav.example.com/samael.example.com/g' samael.example.com
cd ../sites-enabled
sudo ln -s ../sites-available/samael.example.com
sudo apachectl restart

That should be it, right? But when I point my browser to samael.example.com, it's still pointing to the default VirtualHost. What step am I skipping?
cat samael.example.com
<VirtualHost *:80>
    ServerName samael.example.com
    ServerAdmin webmaster@localhost

    DocumentRoot /httpd/www/samael.example.com
    <Directory />
            Options FollowSymLinks
            AllowOverride None
    </Directory>
    <Directory /httpd/www/samael.example.com>
            Options FollowSymLinks
            AllowOverride All
            Order allow,deny
            allow from all
    </Directory>

    ErrorLog /var/log/apache2/samael.example.com-error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog /var/log/apache2/samael.example.com-access.log combined

EDIT:
Per the request in the comments:
sudo apache2ctl -S
VirtualHost configuration:
wildcard NameVirtualHosts and _default_ servers:
*:80                   is a NameVirtualHost
         default server dav.example.com (/etc/apache2/sites-enabled/dav.example.com:1)
         port 80 namevhost dav.example.com (/etc/apache2/sites-enabled/dav.example.com:1)
         port 80 namevhost dev.example.com (/etc/apache2/sites-enabled/dev.example.com:1)
         port 80 namevhost example.com (/etc/apache2/sites-enabled/example.com:1)
         port 80 namevhost new.example.com (/etc/apache2/sites-enabled/new.example.com:1)
         port 80 namevhost samael.example.com (/etc/apache2/sites-enabled/samael.example.com:1)
         port 80 namevhost stage.example.com (/etc/apache2/sites-enabled/stage.example.com:1)
         port 80 namevhost test.example.com (/etc/apache2/sites-enabled/test.example.com:1)
Syntax OK

The output of this is a bit puzzling to me. I would expect the default to be example.com rather than dav.example.com. The configuration file for example.com has ServerAlias * defined in it.

A: It's possible that your vhost configuration file is not being seen by apache, either for lack of an include directive, or a lack of permissions.
Ensure that in your main configuration file you have a directive like
Include /etc/apache2/sites-enabled/*

If it is in a conditional block, such as <IfDefine VHOSTS>, ensure the condition is evaluating to true (eg. by ensuring the correct define is specified or the correct module is loaded).
Also, ensure that whichever user apache is running as (usually apache) has permission to read the file and enumerate the sites-enabled directory.  Specifically, it needs read and execute on the sites-enabled directory, and read on all the configuration files in sites-enabled.
Per your edit, it is probable that the ServerAlias * directive you have is confusing things.  This is not the way to designate a default vhost.  The default vhost, with name-based virtual hosting, is used only when no other virtual host matches (ServerAlias or ServerName), and is simply the first one that is loaded, in alphabetical order.  This is how the dav.example.com host was most likely chosen.  To overcome this, usually the intended virtual host configuration file is named something like 00_default_vhost.conf.
Matching is also done in the order files are read.  So, any sites that aren't dav.example.com or dev.example.com will be matched by example.com with the wildcard alias.


text:
Q: Extensible relational division in LINQ In this example class IcdPatient represents a many-to-many relationship between a Patient table (not shown in this example) and a lookup table Icd.
public class IcdPatient
    {
        public int PatientId { get; set; }
        public int ConditionCode { get; set; }

        public static List<IcdPatient> GetIcdPatientList()
        {
            return new List<IcdPatient>()
            {
                new IcdPatient { PatientId = 100, ConditionCode = 111 },
                new IcdPatient { PatientId = 100, ConditionCode = 222 },
                new IcdPatient { PatientId = 200, ConditionCode = 111 },
                new IcdPatient { PatientId = 200, ConditionCode = 222 },
                new IcdPatient { PatientId = 3, ConditionCode = 222 },
            };
        }
    }
    public class Icd
    {
        public int ConditionCode { get; set; }
        public string ConditionName { get; set; }

        public static List<Icd> GetIcdList()
        {
            return new List<Icd>()
            {
                new Icd() { ConditionCode =111, ConditionName ="Condition 1"},
                new Icd() { ConditionCode =222, ConditionName ="Condition 2"},
            };
        }
    }

I would like for the user to be able to enter as many conditions as they want, and get a LINQ object back that tells them how many PatientIds satisfy that query.  I've come up with:
List<string> stringFilteredList = new List<string> { "Condition 1", "Condition 2" };
            List<int> filteringList = new List<int> { 111,222 };
            var manyToMany = IcdPatient.GetIcdPatientList();
            var icdList = Icd.GetIcdList();
            /*Working method without joining on the lookup table*/
            var grouped = from m in manyToMany
                          group m by m.PatientId into g
                          where g.Count() == filteringList.Distinct().Count()
                          select new
                          {
                              PatientId = g.Key,
                              Count = g.Count()
                          };
            /*End*/
            foreach (var item in grouped)
            {
                Console.WriteLine(item.PatientId);
            }

Let's say that IcdPatient has a composite primary key on both fields, so we know that each row is unique.  If we find the distinct number of entries in filteringList and do a count on the number of times a PatientId shows up, that means we've found all the people who have all conditions.  Because the codes can be esoteric, I would like to do something like
let the user table in the ConditionName in type Icd and perform the same operation.  I've not used LINQ this way a lot and I've gathered:
 List<int> filteringList = new List<int> { 111,222 };
            List<string> stringFilteredList= new List<string>{"Condition 1","Condition 2" };
            filteringList.Distinct();
            var manyToMany = IcdPatient.GetIcdPatientList();
            var icdList = Icd.GetIcdList();
            /*Working method without joining on the lookup table*/
            var grouped = from m in manyToMany
                          join i in icdList on
                          m.ConditionCode equals i.ConditionCode
                          //group m by m.PatientId into g
                          group new {m,i} by new { m.ConditionCode }into g
                          where g.Count() == filteringList.Distinct().Count()
                          select new
                          {

                              Condition = g.Key.ConditionCode

                          };
            /*End*/

but can't get anything to work.  This is essentially a join on top of my first query, but I'm not getting what I need to group on.

A: You don't need to group anything in this case, just use a join and a contains:
List<string> stringFilteredList= new List<string>{"Condition 1","Condition 2" };

var patients =
    from icd in Icd.GetIcdList()
    join patient in IcdPatient.GetIcdPatientList() on icd.ConditionCode equals patient.ConditionCode
    where stringFilteredList.Contains(icd.ConditionName)
    select patient.PatientId;

A:
Let's say that IcdPatient has a composite primary key on both fields, so we know that each row is unique. If we find the distinct number of entries in filteringList and do a count on the number of times a PatientId shows up, that means we've found all the people who have all conditions. Because the codes can be esoteric, I would like to do something like let the user table in the ConditionName in type Icd and perform the same operation.

I believe you're asking:

Given a list of ConditionCodes, return a list of PatientIds where every patient has every condition in the list.

In that case, the easiest thing to do is group your IcdPatients table by Id, so that we can tell every condition that a patient has by looking once. Then we check that every ConditionCode we're looking for is in the group. In code, that looks like:
var result = IcdPatient.GetIcdPatientList()
                    // group up all the objects with the same PatientId
                    .GroupBy(patient => patient.PatientId)
                    // gather the information we care about into a single object of type {int, List<int>}
                    .Select(patients => new {Id = patients.Key,
                                            Conditions = patients.Select(p => p.ConditionCode)})
                    // get rid of the patients without every condition
                    .Where(conditionsByPatient =>
                            conditionsByPatient.Conditions.All(condition => filteringList.Contains(condition)))
                    .Select(conditionsByPatient => conditionsByPatient.Id);

In query format, that looks like:
var groupedInfo = from patient in IcdPatient.GetIcdPatientList()
                  group patient by patient.PatientId
                    into patients
                    select new { Id = patients.Key,
                                 Conditions = patients.Select(patient => patient.ConditionCode) };
var resultAlt = from g in groupedInfo
                where g.Conditions.All(condition => filteringList.Contains(condition))
                select g.Id;

Edit: If you'd also like to let your user specify the ConditionName rather than the ConditionId then simply convert from one to the other, storing the result in filteringList, like so:
var conditionNames = // some list of names from the user
var filteringList = Icd.GetIcdList().Where(icd => conditionNames.Contains(icd.ConditionName))
                                    .Select(icd => icd.ConditionCode);


text:
Q: Parsing CSS 2.1 with the correct CSS parsing conventions in ANTLR The CSS2.1 grammar includes a strong advisory to not parse CSS directly this way, "since it does not express the parsing conventions, only the CSS 2.1 syntax."
Indeed, any parser that ignores these parsing conventions (as we have tried to do) runs into problems when dealing with pages containing errors or unknown constructs.
Therefore, we'd like our CSS2.1 ANTLR parser - which does not currently follow the forward-compatible and error-handling parsing conventions - to somehow use the parse tree generated by the basic grammar that does incorporate the parsing conventions. (The latter could perhaps be generated by another ANTLR parser.)
Is this a reasonable approach? Are there well understood techniques for doing this?
To reiterate, the goal is to produce a robust CSS2.1 parser that can handle errors and new constructs gracefully, in accordance with the CSS parsing conventions.

A: We went with the general approach above that we thought might work; it did.
Briefly, we have two ANTLR parsers: one for the core CSS grammar, and another for the CSS2.1 grammar. The CSS2.1 parser can be executed independently of the core CSS parser. However, that is not how it is actually used.
The core CSS parser is used to construct a basic parse tree. The rule actions re-parse the text using the appropriate entry points of the CSS 2.1 grammar, to produce the same C# objects that the CSS2.1 grammar would have produced when executed standalone. For example, the ruleset action in the core CSS parser re-parses the matched text using the ruleset entry point in the CSS 2.1 grammar, and adds the resulting objects to its result.
A couple of important points that took us a lot of time to figure out:

*

*ANTLR Parser rules that are called from external code are different in the way that they handle EOF's, compared to entry points that are called by other rules.

*The core CSS grammar needs to be augmented depending on which level of CSS is actually being translated to without violating the parsing conventions. One example is the @media at-rule, whose block contains rulesets that needed to be parsed as far as possible using the parsing conventions, before being handed over to the CSS2.1 parser.
Hope this is helpful to others looking to do the same thing.


text:
Q: Does $o_p(1/n)$ mean when $n\rightarrow\infty$ we have an $a.s.$ convergence? If I have two functions (actually estimators), say $A_n(x)$ and $B_n(x)$, and I can prove $\sup_{x\in\mathbb{R}} |A_n(x)-B_n(x)|\leq o_p(1/n)$, can I conclude
\begin{eqnarray*}
\lim_{n\rightarrow\infty} \sup_{x\in\mathbb{R}}|A_n(x)-B_n(x)|=0 \; \; \; a.s.
\end{eqnarray*}
like that? If I can't, is there any way or lemma to prove something like this (strong conistency)? I have tried GC lemma, but it did not work, because my estimators are not step function. Thank you so much in advance


text:
Q: how to create a HTML file on the client's system using webservice (RESTful) Is it possible to create an HTML file on the client's system when the client invokes the RESTful service? The contents of the HTML file is passed as input to the service.
public void GetHTML(string ID, string serviceName, string description)
{
    string content = description;
    string filename = "id_" + ID.Trim();
    string location = @"C:\sd\files\" + filename + ".html";
    FileStream file =
       new FileStream( location, FileMode.OpenOrCreate, FileAccess.Write);
    file.Close();
    File.WriteAllText(location, content);
}


text:
Q: Механизм генерации роутов в шаблонах в spring mvc приложении Нужен механизм генерации роутов в шаблонах в spring mvc приложении.
т.е. в шаблоне указывается конструкция вида
<a href="<route:route controller="MainController.index", parameters={page: 1}/>">main page

и получаем результат в виде сгенерированной ссылки
main page

В спринг как я понял готового механизма роутинга нет, какой лучше плагин использовать ?
A: В принципе вот так url'ы правильно генерятся, с учетом названия приложения, если приложение мапится на url типа http://localhost:8080/app/
<spring:url value="/category/{slug}" var="articleUrl">
    <spring:param name="slug" value="${category.name}" />
</spring:url>

${category.name}


text:
Q: market filter, how to exclude layout-notlong I'm programming an app that is suitable only for devices that have long display.
Now I'm looking after how to setup market filters to prevent download of an application to devices with nolong displays.
Is there a way to do so? Or I have to check aspect ratio in the application and pop an excuse note to user with not proper layout?
Thanks

A: What do you mean long display? If you mean large display, then you can set the supports-screens element in the manifest, specifying with true/false which screen sizes you support.
http://developer.android.com/guide/topics/manifest/supports-screens-element.html#small


text:
Q: Velocity Templates variables and methods. Why does *this* syntax work and *that* syntax doesn't? I am new to Spring MVC and Velocity Templates, but I am using them for a project and had some questions. Basically, I'm using some legacy code as my template, but the syntax in the legacy code isn't working for me and I'm not sure why. Our team has a public class called AdminData which looks something like:
    public class AdminData {
            private long property1;

            public void setProperty1 (long property1) {
                    this.property1 = property1;
            }

            public long getProperty1() {
                    return property1;
            }

And Java code which looks like this:
    ModelAndView model = new ModelAndView("view");
    AdminData data = new AdminData();

    ... // set some properties of data

    model.addObject("data", data);
    return model;

then in our Velocity Template we reference properties of the data object like so:
    ${data.property1}

and the value is correctly displayed on the page. Then we have another class called AdminFeatures which looks like:
    public class AdminFeatures {
            private boolean property2;

            public void setProperty2(boolean property2) {
                    this.property2 = property2;
            }

            public boolean getProperty2() {
                    return property2;
            }

with essentially the same Java code for setting up the model and view as we used for AdminData. The problem I'm running into is that when I try to reference property2 in AdminFeatures in the same way like:
    ${data.property2}

I am unable to print out the value of the variable. However if I use the syntax:
    $data.getProperty2()         // ... or ${data.getProperty2()}

then I am able to print the value of the property. Does this have something to do with difference between boolean vs. Boolean in Java? Or the fact the property1 is a long while property2 is a boolean?
Thank you.

A: Is because property2 is a boolean. The standard method convention for getter/setter for a boolean type are of the form isProperty and setProperty.
So your AdminFeatures class should be:
public class AdminFeatures {
        private boolean property2;
    public void setProperty2(boolean property2) {
            this.property2 = property2;
    }

    public boolean isProperty2() {
            return property2;
    }


text:
Q: Reducing Calls to Firebase vs Reducing Data Redundancy Currently developing an app with a Chat Feature and was wondering if I should prioritize in minimizing the calls to the DB or minimize the data redundancy in the DB.

Sample DB structure
For the users part:
users/
  active/
    $uid/ (Firebase Auth generated)
      username: string
      userPhotoUrl: string

For the chat messages part:
messages/
  chatRooms/
    $chatRoomId/
      dateCreated: timestamp
      title: string

  chatMessages/
    $chatRoomId/
      $messageId/
        createdAt: timestamp
        uid: string
        message: string

As seen in the DB structure, if I retrieve the chat objects (messageId) I'd only be able to retrieve createdAt, uid, message. This is working fine, however, I would also need the username and userPhotoUrl in order to show the desired data on the client side.
Approach: A flow to get the data I need is to make two calls to the DB, one is to get the data from chatMessages node and the other on the users node.
There are two scenarios where I would need these data:

*

*Retrieving multiple chat messages (initially and every time the user decides to view older messages).

*A new chat message is saved to the DB.

For the first scenario, what I would have to do is to first retrieve the list of chatMessages, upon getting them successfully, I would then need to make a call to DB to get the user details (username, userPhotoUrl) for each chat message -- in order to avoid redundancy of calls as well, I'm saving each user details locally (in SharedPrefs), so that if it already exists, I would just get it immediately.

*

*Pros: Minimizes data redundancy in Firebase DB, which saves space.

*Cons: This involves a lot of API calls and would increase the time to actually be able to display the chat messages.

Possible workaround to make things simpler is to have a username and userPhotoUrl for each chat message. E.g.:
$messageId/
  createdAt: timestamp
  uid: string
  username: string
  userPhotoUrl: string
  message: string

*

*Pros: Easier retrieval since it would just be a single call.

*Cons: Data redundancy would be too much.

For the second scenario, I would have to do the same approach every time I detect a child is added to the $chatRoomId. Same pros and cons.

I understand that data redundancy in NoSQL DB is fine, but for a chat app that would contain a lot of messages, and where the message is the data that could contain redundant data, I think it would be quite heavy stored data wise.
Question is, am I right to aim for reducing the data redundancy, trading a lot of API calls in turn? If anyone could suggest a better approach that I might be missing, it'd be appreciated.


text:
Q: reading PHY MII registers using ethtool ioctls I am familiar with the mii-tool IOCTL calls which could be used to access a PHY device's MII registers something like this:
static int mdio_read(int skfd, int location){
 struct mii_data *mii = (struct mii_data *)&ifr.ifr_data;
  mii->reg_num = location;
  if (ioctl(skfd, SIOCGMIIREG, &ifr) < 0) {
      fprintf(stderr, "SIOCGMIIREG on %s failed: %s\n", ifr.ifr_name,
              strerror(errno));
      return -1;
  }
  return mii->out_value;
}

But the linux kenel I am using is 2.6.32 which seems not to support mii-tool IOCTLs and rather supports the newer ethtool, but I don't seem to find any ethtool subcommand which can server the same purpose as above.
How can i use ETHTOOL IOCTLs to do the same thing as I used with mii-tool ioctls, that is read phy's MII registers? Or I can't do it at all?


text:
Q: Google shortner issu So i have a small PHP script to generate short links, it work but some times i got this error :

Undefined property: stdClass::$id","file":ShortLink.php","line":31

This is my script :
<?php

class ShortLink {

public static function generateShortLink($longUrl)
{
    //This is the URL you want to shorten
    $apiKey = 'MY_API_KEY';
    //Get API key from : http://code.google.com/apis/console/

    $postData = array('longUrl' => $longUrl, 'key' => $apiKey);
    $jsonData = json_encode($postData);

    $curlObj = curl_init();

    curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
    curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curlObj, CURLOPT_HEADER, 0);
    curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
    curl_setopt($curlObj, CURLOPT_POST, 1);
    curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);

    $response = curl_exec($curlObj);

    //change the response json string to object
    $json = json_decode($response);

    curl_close($curlObj);

    return $json->id;
   }

 }

When i start worked with this script 6 or 7 months ago i hadn't this error but now i start get it and i have no idea why, so please if someone has any idea i will be very appreciative.
Update :
When i vardump my $json i get that :
{ ["domain"]=> string(11) "usageLimits" ["reason"]=> string(26) "userRateLimitExceededUnreg" ["message"]=> string(40) "User Rate Limit Exceeded. Please sign up" ["extendedHelp"]=> string(36) "https://code.google.com/apis/console" } } ["code"]=> int(403) ["message"]=> string(40) "User Rate Limit Exceeded. Please sign up" }}

So i wondered if Google limited the Google shorten service ?

A:
class ShortLink {
public static function generateShortLink($longUrl)
{
    //This is the URL you want to shorten
    $apiKey = 'YOUR_SERVER_API_KEY';
    //Get API key from : http://code.google.com/apis/console/

    $postData = array('longUrl' => $longUrl, 'key' => $apiKey);
    $jsonData = json_encode($postData);

    $curlObj = curl_init();

    curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
    curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curlObj, CURLOPT_HEADER, 0);
    curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
    curl_setopt($curlObj, CURLOPT_POST, 1);
    curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);

    $response = curl_exec($curlObj);

    //change the response json string to object
    $json = json_decode($response);

    curl_close($curlObj);
    if(!is_object($json))
    {
        return(false);
    }
    return $json->id;
   }

}
$api = new ShortLink();
$shorturlid=$api->generateShortLink('http://avecsrthgdgnb.avcd');
echo $shorturlid;

are you using new console then enable URL Shortener API.

A: Sometimes because of network curl is not returned with response within 30 seconds (default time limit in php for a cmd to finish)
Try changing the time limit in php.ini or if that is not in your control or you do not want to modify it for all the php cmds try bool set_time_limit ( int $seconds ) before calling curl_exec
Update:
I see there is no id field in the json that is returned.
{ ["domain"]=> string(11) "usageLimits"
  ["reason"]=> string(26) "userRateLimitExceededUnreg"
  ["message"]=> string(40) "User Rate Limit Exceeded. Please sign up"
  ["extendedHelp"]=> string(36) "https://code.google.com/apis/console"
}
}
  ["code"]=> int(403)
  ["message"]=> string(40) "User Rate Limit Exceeded. Please sign up"
}
}

And if you closely see your User rate limit has been reached See here for details on limitation on using google apis. (You may try different IP i.e. different machine or different api key and same code may start working).
Hope this helps


text:
Q: How to capture back button of the browser without using pushstate? I have tried capturing the back button action on the browser using pushstate and popstate but problem is pushstate alters the history, thus affecting the normal functioning of back button.

A: Most people recommend using:
window.onhashchange = function() {
    if (window.innerDocClick) {
        window.innerDocClick = false;
    } else {
        if (window.location.hash != '#undefined') {
            goBack();
        } else {
            history.pushState("", document.title, window.location.pathname);
            location.reload();
        }
    }
}
function goBack() {
    window.location.hash = window.location.lasthash[window.location.lasthash.length-1];
    //blah blah blah
    window.location.lasthash.pop();
}

A: Create an Array that collects the window.location.hash of the user with every change made to window.location.lasthash.
const updateHistory = (curr) => {
    window.location.lasthash.push(window.location.hash);
    window.location.hash = curr;
}

Unfortunately, there's no native event fired for clicking the browser's back button. However, there is a nice method to faking it using a combination of other native event listeners.
First, set a boolean that gets toggled each time the document is rendered by listening for the onmouseover event.
const onDocRenderHandler = (bool) => {
    window.innerDocClick = bool;
}

document.onmouseover = onDocRenderHandler(true)

After the user clicks the back button, the document again renders so set the boolean flag to toggle again; only this time listening for the onmouseleave event to fire.
document.onmouseleave = onDocRenderHandler(false)

Finally, listen for theonhashchange event to fire in between document renders. This simulates a pseudo back button event for us to listen and act on.
const onHashChangeHandler = () => {
    if(!window.innerDocClick) {
        history.pushState("", document.title, window.location.pathname);
        location.reload();
    }
}
window.onhashchange = onHashChangeHandler()


text:
Q: tkinter button reffer self atribute A have a Grid of 38 buttons (num0-num38).
I'm trying to pass the button attribute (text) to the print function.
Code:
def collect_num(num):
    print(num)

num0 = tk.Button(buttons, text="0", padx=10, pady=5, fg="white", bg="green", command=collect_num(thisItem.text))

Is there something similar to thisItem.text in Python?
So basically, I would like to print the button name (text="0" - text="38") when the correspondent button is pressed.
Any help with that is appreciated.

A: you need pass the button text using partial(<function>, *args) function
from functools import partial

def collect_num(num):
    print(num)

# create the button first and add some specs like `text`
button = tk.Button(
  buttons, text="0", padx=10, pady=5, fg="white", bg="green"
)

# add command after creation with the above function and button's name
button.config(command=partial(collect_num, button["text"]))

with the help of this stack question:
text = button["text"]

this is the method with which you can get the text.
or
text = button.cget('text')

or (with the help of @TheLizzard)
text = button.config("text")[-1]

A: Since you asked for an example, take a look here:
from tkinter import *

root = Tk()
MAX_BUTTON = 25 # Maximum number of buttons to be made

def collect_num(num):
    print(num) # Print the number

btns = [] # A list to add all the buttons, to make them reusable later
for i in range(MAX_BUTTON): # Looping 25 times or maximum number of buttons, times
    btns.append(Button(root,text=i,width=10))  # Creating a button and adding it to list
    btns[-1]['command'] = lambda x=btns[-1].cget('text'): collect_num(x) # Changing the command of the button
    btns[-1].pack() # Packing it on

root.mainloop()

Here cget() returns the current properties of the widget.
It is highly recommended to do this, instead of creating buttons one by one manually. There is a principle in software engineering called DRY which means Don't Repeat Yourself, which usually means if your repeating yourself, there will possibly be a way to not repeat your self and reduce the code written. And this looping and creating a widget and using lambda to make the command is quiet used frequently when needed to make more than one widget with a pattern.


text:
Q: RoR - Where to put/initialize constant for a lib module In my Rails 3 application, I have a module in the lib/ folder. The module requires a constant variable, which is a big dictionary loaded from a data file. Since the dictionary won't change over the course of the application and its time consuming to reload this data file everytime a method from the module is called, I want to create a constant which holds the dictionary that can be accessed by the module in the lib.
lib/my_module:
module My_Module
   def do_something(x)
      y = CONSTANTVAR[x]
      ...
   end
end

to initialize the constant, I have to load a file:
file = File.new('dataFile.dat','r') #I'm not sure where to put this data file
file.each_line { |line|
             lineInfo = line.split
             CONSTANTVAR[line[0]] = line[1] }
file.close

Where is the standard place to initialize variables that can be accessed by modules in the lib folder (this is the only place I will be accessing the variable)?
Also, the module loads a data file, is it standard to put data files in the lib/ folder as well?
Thanks!

A: I should put my, say, init_dictionary.rb in config/initializers. I think it's the better place for your requirement.

A: You can take a look on how it is done here: https://github.com/sevenwire/forgery
It is a lib for generating words and it uses dictionaries. They are saved in : /lib/forgery/dictionary/*
So, save you dictionary on /lib/module-name/dictionaries/DATA.dat
And you can initialise your variable in config/initialisers/module-name.rb


text:
Q: Check each row of datagridview and get value of column(s) I have a datagridview that is populated with a couple of rows. I not sure where to start to loop the grid from row 1 to the last row and check some values on two of the columns. My grid looks like this, I need to check the values of r1:c1 and r1:c4 using a loop. my c1 is checkbox column by the way.
   c1  c2  c3  c4  c5
r1 true    4    5   5   5
r2 false   4    5   5   5
r3 false   8    6   4   5
r4 false   5    1   2   3
r5 false   4    1   2   1

I've tried:
For Each row As DataGridViewRow In datagrid.Rows
        If row.Cells("column1").Value = True Then
            Dim getValue As String
            getValue = row.Cells("column4").Value
            msgbox(getValue)
        End If
Next

Problm is, if any cell in column 1 is true, getValue is still getting set the value in column4. I only want the column4 value if column 1 row is true.

A: EDIT:
This is what I'm using for the same purpose as you, but i'm checking for Strings/Integers so not sure how it would translate to boolean, and it works for returning a value of column 4-row(i) when you check the value of column 1-row(i). Hope this helps at least.
    For i = 0 To YourDataGridHere.RowCount - 1
        If Not (YourDataGridHere.Rows(i).Cells("Column1").Value = 0) Then
            MsgBox(YourDataGridHere.Rows(i).Cells("Column4").Value)
        End If
    Next


text:
Q: Attempting to read user input from jtextfield and display in another jtextfield. Comes up null I am new to java and I just can't seem to solve this issue. I know I am missing something.
Basically what I am attempting to do is read the input from a user in a JTextfield and then display what the user entered into another JTextfield.
I want all this to occur after I hit the add button.  Once I hit the add button I want the user input from the first JTextfield to then be displayed in a different JTextfield.
However when in input something into the first text field and hit the add button I get a null value in the other JTextfield.  I can't figure out why.
I am using class variables that are supposed to store what the user inputs using the .gettext() method.
Not sure what is going on any help is appreciated.
package inventoryprogrampart6;

import javax.swing.JFrame;

public class AddItemWin extends javax.swing.JFrame {
  private int itNm,unitNm,yr;
  private String prodName;
  private double price;
    /**
     * Creates new form AddItemWin
     */
    public AddItemWin() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        textField1 = new java.awt.TextField();
        textField2 = new java.awt.TextField();
        textField3 = new java.awt.TextField();
        textField4 = new java.awt.TextField();
        textField5 = new java.awt.TextField();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Add New Item", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Times New Roman", 1, 12))); // NOI18N

        jLabel1.setText("Item Number:");

        jLabel2.setText("Product Name:");

        jLabel3.setText("Number of Units:");

        jLabel4.setText("Prodcut Price");

        jLabel5.setText("Year Made:");

        jButton1.setText("Add Item");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(textField1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(textField2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(textField3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(textField4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(textField5, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(157, 157, 157)
                        .addComponent(jButton1)))
                .addContainerGap(156, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel1)
                                    .addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(textField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel3))
                            .addComponent(textField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4))
                    .addComponent(textField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel5)
                    .addComponent(textField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(21, 21, 21)
                .addComponent(jButton1)
                .addContainerGap(23, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(76, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
       textField5.setText(String.valueOf(getitNm()));

    }

   public void addToArray()
   {
        itNm = Integer.parseInt(textField1.getText());
        prodName = (textField2.getText());
        unitNm = Integer.parseInt(textField3.getText());
        price = Double.parseDouble(textField4.getText());
        yr = Integer.parseInt(textField5.getText());

   }

    public int getitNm()
    {
        return itNm;
    }

    public String getProdName()
    {
        return prodName;
    }
    public int getunitNm()
    {
        return unitNm;
    }
    public double getprice()
    {
        return price;
    }
    public int getyear()
    {
        return yr;
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private java.awt.TextField textField1;
    private java.awt.TextField textField2;
    private java.awt.TextField textField3;
    private java.awt.TextField textField4;
    private java.awt.TextField textField5;
    // End of variables declaration
}

A: You are not calling this method anywhere in your class
 public void addToArray()

That is why the values which you enter are not stored

A: First of all, you don't need all that extra code, it just wastes memory. Take out the package names when instantiating a type. Second, you can't just parse for certain text right out of a text field, you have to put the value in a string first. If that doesn't work try
 myTextBox.setEnabled(true);

If you need any more help ask me.

A: There are a number of problems, mostly revolving around issues with not actually know what it is you are trying to achieve...
This will cause an error if any of the fields has no text (or text that can't be paresed as a int)
public void addToArray() {
    itNm = Integer.parseInt(textField1.getText());
    prodName = (textField2.getText());
    unitNm = Integer.parseInt(textField3.getText());
    price = Double.parseDouble(textField4.getText());
    yr = Integer.parseInt(textField5.getText());
}

This means, if you leave the last field blank, it through a NumberFormatException.  Now, the fact that you want to copy the contents of this first field to the last field makes me wounder why you want the contents for this field.
In you jButton1ActionPerformed method, you could simply use textField5.setText(textField1.getText()) and achieve what you want


text:
Q: Finding the norm of the given operator Let's define an operator:
$$T: L^p([0, 1]) \to L^p([0, 1]),$$
$$(Tf)(x) = xf(x).$$
Where $L^p = \big\{ f: \int \limits_{0}^{1}|f(x)|^p \mbox{d}x < \infty \big\}$.
We are to find the norm of the given operator.
Firstly I managed to show that:
$$|| Tf ||^p = \int\limits_0^{1} |x|^p|f(x)|^p \mbox{d}x \le \int \limits_{0}^{1} |f(x)|^p \sup_{x \in[0, 1]}|x|^p \mbox{d}x = ||f||^p.$$
Thus we suspect that $||T|| = 1$.
Now we just need to find an element from $L^p([0, 1])$ such that it's norm is equal to $1$. What should the element look like?

A: If you want to find some $f$ such that $\|Tf\|/\|f\| = 1$, take a look at the inequality you found which yielded $\|Tf\| \leq \|f\|$, and see if you can find a case which makes it an equality. You determined this by making the estimate:
$$
|x|^p \leq \sup \limits_{x \in [0,1]} |x|^p
$$
This is not a very sharp estimate. In fact, for any $t \in (0,1)$, we could rewrite your estimate to get:
$$
\|Tf\|^p
=
\int \limits_0^1 |f(x)|^p |x|^p dx
\leq
t^p \int \limits_0^t |f(x)|^p dx
+
\int \limits_t^1 |f(x)|^p dx
\\
\leq
\int \limits_0^1 |f(x)|^p dx
=
\|f\|^p
$$
But here, this last inequality is only an equality if $f$ is zero on $[0,t]$. So, it seems like the only function which gives you an equality is the zero function, but this doesn't help you find the norm.
Instead, you could try finding a sequence of functions $(f_n)_n$ such that $\|Tf_n\|/\|f_n\| \rightarrow 1$: this also would let you prove that $\|T\|=1$. But how to find this sequence? Again, we look at the estimate you made to get your inequality $\|Tf\| \leq \|f\|$. What functions could you pick to minimize the effect of your estimate? Since you used the estimate with $\sup_{x \in [0,1]} |x|^p$, it makes sense to look for functions which are "concentrated" near 1, since this is where the difference between $|x|^p$ and $\sup_{x \in [0,1]} |x|^p$ is the smallest. In particular, as it's been pointed out in the comments, you could try the characteristic function on $[1-\frac{1}{n}, 1]$.


text:
Q: Showing a branch which i not even there in Github The repo have only one branch(i.e, main) is also the default one but while opening the files it is showing a branch name 'b3c52f83e0'.
What's the issue?

A: It would be not the name of a branch, but a SHA1 of a commit.
Check your GitHub project commits history and see if that commit does exist.
You cal also check that locally by cloning the same repository, and using  git log.


text:
Q: How run subprocess in Python 3 on windows for convert video? I have a little problem, I have trying for a lot time converted a video with FFMPEG in python 3 like this:
The model,
class Video(models.Model):
   name = models.CharField(max_length=200, null=False)
   state = models.CharField(max_length=30, null=False)
   user_email = models.CharField(max_length=30, null=False)
   uploadDate = models.DateTimeField(null=False)
   message = models.CharField(max_length=200, null=False)
   original_video = models.FileField(upload_to='video', null=True)
   converted = models.BooleanField(default=False)

And the code of converted.
video = Video.objects.filter(id=param_id).get()
pathConverted = 'C:\\Users\\diego\\Documents\\GitHub\\convertido.mp4'
cmd = ['ffmpeg', '-i ', video.original_video.path, ' -b 1500k -vcodec ibx264 -g 30', pathConverted]
print('Ejecutando... ', ' '.join(cmd))
try:
    proc = subprocess.run(cmd, shell=True, check=True)
    proc.subprocess.wait()
except subprocess.CalledProcessError as e:
    raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))

The error is this.
 raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output)) RuntimeError: command '['ffmpeg', '-i ', 'C:\\Users\\diego\\Documents\\GitHub\\video1.avi', ' -b 1500k -vcodec libx264 -g 30', 'C:\\Users\\diego\\Documents\\GitHub\\convertido.mp4']' return with error (code 1): None

And also I have tried this:
video = Video.objects.filter(id=1).get()
pathConverted = 'C:\\Users\\diego\\Documents\\GitHub\\convertido.mp4'
cmd = ['ffmpeg', '-i ', video.original_video.path, ' -b 1500k -vcodec libx264 -g 30', pathConverted]
print('Ejecutando... ', ' '.join(cmd))
proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
proc.subprocess.wait()

In this case the error is:
FileNotFoundError: [WinError 2] No such file or directory

But when I copy the path and paste this in CMD on windows for try this converted the video. It works fine.
Then, I am confused, I don't understand what is the error.
Somebody can help me please?

A: The file not found is file "ffmpeg".
Try to enter file with path and extension : c:\Program Files\ffmpeg\ffmpeg.exe
Best Regard
Emmanuel


text:
Q: Safely deleting a commit after git amend and git push --force I am not a git expert and I am trying to save code that I am working on.
I wanted to rename the most recent commit by following the steps described here.
Particularly, I first ran
git commit --amend

to correct misspelled commit message using a text editor locally,
then
git push --force

to update GitHub repository.
Everything went well except that I still have a (I believe, sorry for a bad terms) upstream changes labeled red in git gui:

That say

Local uncommitted changes, not checked in to index

This red labeled changes are the same as my recently amended commit. Running git pull just says that

Already up to date

So, my question is how to remove those 'duplicate' changes? (node labelled red on the picture above).
I am afraid that running: git reset --hard HEAD^ will just remove the last amended commit

A: I solved this issue by simply making changes to the file that was in upstream node (labelled red) captioned

Local uncommitted changes, not checked in to index

and committed it.
The "Local uncommitted changes, not checked in to index" were overridden by my new commit


text:
Q: Retrofit converts json array to string I want to post a json array (the users in the following json object) to a server:
// Acceptable request because the 'users' is a json array
{"users": [{"name": "Mike", "role": "editor"}, {"name":"Alice", "role": "admin"}]}

The server accepts the users as a json array not a string. But, the retrofit converts the users to a string by adding quotation marks to it like this:
// Unacceptable request because the 'users' is a string
{"users": "[{"name": "Mike", "role": "editor"}, {"name":"Alice", "role": "admin"}]"}

Here is my retrofit codes:
// interface
@FormUrlEncoded
@POST("users/store")
Call<ResponseBody> storeUser(@Field("users") JSONArray users);

// implementation
String users = "[{\"name\": \"Mike\", \"role\": \"editor\"}, {\"name\":\"Alice\", \"role\": \"admin\"}]";
JSONArray jsonArrayUsers = new JSONArray(users);
userViewModel.storeUser(jsonArrayUsers).observe(...)

So, how can I send the users as a json array to the server without allowing retrofit to convert it to string?


text:
Q: Implicit & Explicit QR algorithms & non-convergence I have been working with the matrix below:-
\begin{pmatrix}
8 & -2 & 1 & -1 \\
23 & -6 & 3 & -3 \\
-4 & 1 & 1 & 1 \\
-4 & 2 & 0 & 1 \\
\end{pmatrix}
It's eigenvalues are {1,1,1,1}. I have my own program that implements the implicit version of the QR algorithm, and also another than implements the explicit version of it.
I have tested this matrix on some online eigenvalue finders, and most of them return the correct answer of {1,1,1,1}, however the version of Mathcad that I own returns values that are close to, but not exactly equal to one. In fact, they even have small imaginary components.
My own implicit QR returns similar values, and I cannot seem to encourage it to hone in on precisely '1'. However, my explicit version produces the correct values.
Any idea what is going on here? Is it that the explicit version, although slower, is more 'numerically robust' than the implicit?
Regards
Jeremy Watts

A: Matrix
$$M=\begin{pmatrix}
8 & -2 & 1 & -1 \\
23 & -6 & 3 & -3 \\
-4 & 1 & 1 & 1 \\
-4 & 2 & 0 & 1 \\
\end{pmatrix}$$
Some important facts:
1) The Jordan form of matrix $M$ is $M=PJP^{-1}$ with
$$J=\begin{pmatrix}
     1  &   1  &   0   &  0\\
     0  &   1  &   1 &    0\\
     0   &  0  &   1  &   1\\
     0  &   0  &   0  &   1
\end{pmatrix} \ \ \text{and} \ \ P=\begin{pmatrix}
    -6   &  3  &   7  &   1\\
   -12   &  0  &  23  &   0\\
     6  &  -9  &  -4  &   0\\
   -12  &  18  &  -4  &   0\\
\end{pmatrix}$$
2) This Jordan form means that $1$ is an eigenvalue with multiplicity 4, but with a dimension 1 associated eigenspace (directed by $(1,2,-1,2)^T$). We are far from the diagonalizable case.
3) Matlab, known for its accuracy in all its basic algorithms, gives (as you have had) eigenvalues that are not equal to 1:
$$0.9998 \pm 0.0002i, \ \ \  \ 1.0002 \pm 0.0002i$$
4) The condition number of $M$ is rather high : around $10^3.$
(I assume that Matlab uses a variant of QR algorithm for computing eigenvalues)
Besides these observations, I have no simple explanation.
Remark:
I have been able to reconstruct a similar example by defining
$M_1:=P_1JP_1^{-1} \ \ \text{with}$
$$ M_1:=\begin{pmatrix}
   -2  &  6 &  -4 &  1\\
   -1  &  2 &   0  & 0\\
    0  & -1  &  2 &  0 \\
    0  &  0  & -1  & 2
\end{pmatrix} \ \ \ \ and \ \ \ \ P_1:=\begin{pmatrix}
     1  &   1   &  1  &   1\\
     1  &   2  &   3   &  4\\
     1  &   3  &   6  &  10\\
     1  &   4  &  10  &  20
\end{pmatrix} \ \ \text{known as Pascal's matrix}$$
with eigenvalues that should be $1$ but that are found, by Matlab, to be:
$$\{0.9997 + 0.0000i, \ 1.0000 + 0.0003i, \ 1.0000 - 0.0003i, \ 1.0003 + 0.0000i\}$$
May I ask you to test $M_1$ with your code and say if the same phenomena occur ?
(this time, $\det(P_1)=1$ whereas, in the case of the problem, $\det(P)=1296.$)

Edit: I have defined the same matrices as just above, by $8 \times 8$ instead of $4 \times 4$ ; the phenomenon takes a much larger amplitude (incertitude multiplied by $\approx 10^2$ !):
$$\{0.9336, \ \ \ 0.9542 \pm 0.0473i, \ \ \ 1.0012 \pm 0.0648i, \ \ \ 1.0458 \pm 0.0449i, \ \ \ 1.0641 \}.$$


text:
Q: read environment variable in vuejs application after creating build or docker image I am building a docker image for my vuejs app. And I want some environment variable to read by my vuejs application.
For example:
I want to change my 'baseUrl' after creating and building the image, in runtime environment.
What I've tried & Search is:
It says you can not read outside an application after creating vuejs application build.

A: Check the docs of React example. You can inject to the html any variable at runtime (from backend, server side). Here the simple schema used in React.
html:
<script>
window.SERVER_DATA = __SERVER_DATA__;
</script>

client:
const  constants = {
    debug: false,
    port: 8443,
    host: window.SERVER_DATA,
    graphql: {
        path: '/graphql'
    },
}

On the server side use the functions to pipe (and change your variable) the html output to client.


text:
Q: Clone crossbeam channel How do you access a crossbeam channel "send" from every actix-ws callback?
This is a version of this asked on a specific example with a beautiful MRE.
Specifically, I've made as few changes as possible to the actix-ws example server to keep it neat + simple.
The exact problem is to access "send" on the first commented line ('// use "send"...')

use actix_web::{middleware::Logger, web, App, Error, HttpRequest, HttpResponse, HttpServer};
use actix_ws::Message;
use futures_util::StreamExt;

async fn ws(req: HttpRequest, body: web::Payload, send: crossbeam::channel::Sender<u32>) -> Result<HttpResponse, Error> {
    // use "send", possible cloned

    let (response, mut session, mut msg_stream) = actix_ws::handle(&req, body)?;

    actix_rt::spawn(async move {
        while let Some(Ok(msg)) = msg_stream.next().await {
            match msg {
                Message::Ping(bytes) => {
                    if session.pong(&bytes).await.is_err() {
                        return;
                    }
                }
                Message::Text(s) => println!("Got text, {}", s),
                _ => break,
            }
        }

        let _ = session.close(None).await;
    });

    Ok(response)
}

#[actix_web::main]
async fn main() -> Result<(), anyhow::Error> {
    let (send, recv) = crossbeam::channel::unbounded();

    HttpServer::new(move || {
        App::new()
            .wrap(Logger::default())
            .route("/ws", web::get().to(|req: HttpRequest, body: web::Payload| {
                ws(req, body, send);
            }))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await?;

    Ok(())
}

Error:
error[E0277]: the trait bound `[closure@src/file:35:41: 35:79]: Handler<_>` is not satisfied
   --> src/file:35:41
    |
35  |               .route("/ws", web::get().to(|req: HttpRequest, body: web::Payload| {
    |  ______________________________________--_^
    | |                                      |
    | |                                      required by a bound introduced by this call
36  | |                 ws(req, body, send);
37  | |             }))
    | |_____________^ the trait `Handler<_>` is not implemented for closure `[closure@src/fuck-so.rs:35:41: 35:79]`
    |
note: required by a bound in `Route::to`

A: A few issues are happening here:

*

*Your posted error is because your closure doesn't return anything and returning () isn't a valid response for a Handler. However, all you need to do is remove the ; after ws(...).

*The closure must not reference the local variable send because handlers must be 'static. You can fix that by using the move keyword so any captured variables are moved into your closure:
web::get().to(move |req: HttpRequest, body:
           // ^^^^

*The closure for HttpServer::new() can be called multiple times since its constrained by Fn. In this case, we've already moved send in but we need to also move it out. You can do this by .clone()-ing it within the closure (fortunately crossbeam Senders are cheap to clone):
HttpServer::new(move || {
    let send = send.clone(); // need to make a new copy to move into the route handler
    App::new(...

*Again, in your route closure, you can't move the variable by passing it to ws(...) since it needs to be called multiple times. In other situations you could just pass by reference, Sender doesn't require ownership to do anything, but because async functions return Futures that capture their arguments and functions are not allowed to return values that reference their captures, you'll need to .clone() it anyway:
ws(req, body, send.clone())
               // ^^^^^^^^

With those changes, your code compiles. Here's the full fix:
use actix_web::{middleware::Logger, web, App, Error, HttpRequest, HttpResponse, HttpServer};
use actix_ws::Message;
use futures_util::StreamExt;

async fn ws(
    req: HttpRequest,
    body: web::Payload,
    send: crossbeam::channel::Sender<u32>,
) -> Result<HttpResponse, Error> {
    // use "send", possible cloned

    let (response, mut session, mut msg_stream) = actix_ws::handle(&req, body)?;

    actix_rt::spawn(async move {
        while let Some(Ok(msg)) = msg_stream.next().await {
            match msg {
                Message::Ping(bytes) => {
                    if session.pong(&bytes).await.is_err() {
                        return;
                    }
                }
                Message::Text(s) => println!("Got text, {}", s),
                _ => break,
            }
        }

        let _ = session.close(None).await;
    });

    Ok(response)
}

#[actix_web::main]
async fn main() -> Result<(), anyhow::Error> {
    let (send, recv) = crossbeam::channel::unbounded();

    HttpServer::new(move || {
        let send = send.clone();
        App::new().wrap(Logger::default()).route(
            "/ws",
            web::get().to(move |req: HttpRequest, body: web::Payload| ws(req, body, send.clone())),
        )
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await?;

    Ok(())
}


text:
Q: NSFetchResultsController sorting is not working when inserting new entity I have an CoreData entity called "MyPhoto" with the attributes :- photoData, timeStamp, folderName. Setting the today Date with Time to timeStamp property when saving photoData to core data. I want sections with folderName and inside the section I want to sort the photos with timeStamp. I am using and NSFetchResultsController to fetch the data & UICollectionView to display it.
Problem is: When I try to insert the new photo, it is not inserting in the correct sorting order but when I relaunch the app, it will show the all the photos in a correct sorting order.
here is the code I am using:
- (NSFetchedResultsController *)fetchedResultsController
{
    if (_fetchedResultsController != nil)
    {
        return _fetchedResultsController;
    }

    /*
     Set up the fetched results controller.
     */
    // Create the fetch request for the entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    NSManagedObjectContext *moc = [[CoreDataManager sharedInstance] managedObjectContext];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyPhoto" inManagedObjectContext:moc];
    [fetchRequest setEntity:entity];

    // Set the batch size to a suitable number.
    [fetchRequest setFetchBatchSize:20];

    // Sort using the timeStamp property.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"folderName" ascending:YES];
    NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO];
    [fetchRequest setSortDescriptors:@[sortDescriptor, sortDescriptor1]];

    // Use the folderName property to group into sections.
    _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:moc sectionNameKeyPath:@"folderName" cacheName:@"Root"];
    _fetchedResultsController.delegate = self;

    return _fetchedResultsController;

}

I hope I have explained my problem clearly. Thanks in advance for your help.

A: I see you are setting the delegate. Have you actually implemented any of the delegate methods?
For starters, you could just call reloadData in controllerDidChangeContent:


text:
Q: QtXml linking issue OSX file not found for architecture x86_64 (but file IS x86_64) I'm trying to compile a Qt creator project that uses QtXml, and everything is happy except for the fact that apparently QtXml is not the right format. The linking flags are:
-F/Library/Frameworks -L/Library/Frameworks -L../../../lib/ -lutils -framework QtTest -framework IOKit -framework Security -framework ApplicationServices -framework QtCore -framework QtGui

and then the linker complains with
ld: file not found: QtXml.framework/Versions/4/QtXml for architecture x86_64

BUT file gives me:
file /Library/Frameworks/QtXml.framework/Versions/4/QtXml
/Library/Frameworks/QtXml.framework/Versions/4/QtXml: Mach-O 64-bit dynamically linked shared library x86_64

So I'm confused, the file is there, seems to be the right architecture, but no banana.
does anyone know what's going on ?
thanks,
Jonathan

A: got it, I was compiing with Clang (LLVM) should've compiled with gcc (probably the Mach-O should've tipped me off, could anyone elaborate on this ?)
J