text:
Q: Cocoapods OpenSSL undefined symbols arm64 I'm trying to use OpenSSL in my project through Cocoapods, but it just keeps failing on some "undefined symbols for arm64".
While I know that this question had been asked before; I can't get it to work using the provided solutions. It's really and I mean really frustrating.
I tried the solutions posted in:

*

*Undefined symbols for architecture arm64

*XCode - undefined symbols for architecture armv7 arm64
All the things I did and the configs:

*

*Tried building with the Build Active Architectures for both Debug and Release to YES and tried it with both for NO (in My Project, the Pods project and all the Targets)

*Tried building with the Valid architectures to arm64 arm7 arm7s and all possible variations you can think of with those three

*My project has the linker flags and library/framework search paths set to $(inherited)

*Removed duplicate linker flags or library/framework search paths

*I have added the Pods-{My Project} lib to My project

*Re-installed all the pods by:

*

*Deleting all installed pods

*Deleting the Podfile

*Called pod init

*Added each pod one step at a time

*Re-added the target in My Project and did all the steps again

Next to the above list I probably did a lot of other things I cannot even remember through my clouded-vision right now.
Now this is how my project is set up:
I have a main project which builds my framework. Now because I use both SQLCipher and OpenSSL and had the transitive dependencies error, I added a static library target to my project. This static library target has the Cocoapods dependencies for SQLCipher and OpenSSL which enabled me to use use_frameworks for the framework target in my project.
So far so good and everything works fine, but whenever I try to use OpenSSL in my static library it complains about the godforsaken undefined symbols. I can't seem to resolve those.
Does anyone knows what goes wrong? Or are there other/better setups for what I'm trying?


text:
Q: Sublime Text 3 Windows Python NO Chart generated I am using Sublime Text 3 Windows to run Python (Anaconda) to generate a chart:
import matplotlib.pyplot as plt
heads = [range(1000)]
plt.hist(heads, bins=10)

But after I press Ctrl+B, nothing happened without any error message.
But I can not find the chart anywhere. Where should I do?

A: Add the line
plt.show()

to the end of the code, and run that instead.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ChildActionOnly output cache not disabled I have the following Action in a controller marked with [ChildActionOnly]:
[OutputCache(Duration = 3600)]
public PartialViewResult SideNavigation()
{
    SideNavigationModel model = _sideNavigationFactory.GetSideNavigation();

    if (model != null)
    {
        return PartialView(model);
    }

    return default(PartialViewResult);
}

Which works fine when I call it with:
@Html.Action("SideNavigation", "Template")

In my main template.  However I have noticed that when I update the cshtml file of the side navigation, it does not update on the webpage even though my output caching is disabled in the web.config:
<outputCache enableOutputCache="false">

If I change the main template this is on, that will update but the navigation part of the template won't.  Is this expected behaviour?  If so is there a way to output cache it only when output caching is enabled?

A: using System.Web.Configuration;
using System.Web.Mvc;

namespace Mvc.Filters
{
    public class ExtendedOutputCacheAttribute : OutputCacheAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!web.config.caching.disabled) // just read the right config setting somewhere
            {
               base.OnActionExecuting(filterContext);
            }
        }
    }
}

A: Thanks to a mixture of the this answer and the answer provided by Laurent, I have come up with the following solution using a custom attribute:
public class ChildActionOutputCacheAttribute : OutputCacheAttribute
{
    private const string _cachingSection = "system.web/caching/";
    private const string _outputCacheSection = "outputCache";
    private const string _profileSection = "outputCacheSettings";
    private bool _profileEnabled;

    public ChildActionOutputCacheAttribute(string cacheProfile)
    {
        // get output cache section of web config
        OutputCacheSection settings = (OutputCacheSection)WebConfigurationManager.GetSection($"{_cachingSection}{_outputCacheSection}");

        // check section exists and caching is enabled
        if (settings != null && settings.EnableOutputCache)
        {
            // if caching enabled, get profile
            OutputCacheSettingsSection profileSettings = (OutputCacheSettingsSection)WebConfigurationManager.GetSection($"{_cachingSection}{_profileSection}");
            OutputCacheProfile profile = profileSettings.OutputCacheProfiles[cacheProfile];

            if (profile != null && profile.Enabled)
            {
                // if profile exits set profile params
                Duration = profile.Duration;
                VaryByParam = profile.VaryByParam;
                VaryByCustom = profile.VaryByCustom;

                _profileEnabled = true;           // set profile enable to true as output cache is turned on and there is a profile
            }
        }
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (_profileEnabled)
        {
            // only run this if caching has been set and is enabled
            base.OnActionExecuting(filterContext);
        }
    }
}

This can then been added to the child action controller using the following:
[ChildActionOutputCache(CacheProfile.Long)]

If you have the following sections in your web.config:
<system.web>
  <caching>
    <outputCache enableOutputCache="false"></outputCache>
    <outputCacheSettings>
      <outputCacheProfiles>
        <add name="Long" duration="86400" varyByParam="*" varyByHeader="none" location="Server" />
      </outputCacheProfiles>
    </outputCacheSettings>
  </caching>
</system.web>


text:
Q: Jekyll: Week numbers in Europe for my Jekyll project I need to work with week numbers for certain dates. The problem is that the returned week number does not match with the german one.
I have set the timezone in config.yml:
timezone: Europe/Berlin
For example:
{{ 2019-12-31 | date: "%W" }}
returns
52
1 would be correct. I've tested this on various dates. The week number is never matching, always shifted by 1 or 2 numbers. Does anyone have any idea how to fix the problem?
Thanks!
S.


text:
Q: How to handle data loading with asynctask I am loading data for a log. It runs smoothly. However, I added a gone indeterminate progress bar below toolbar which always shows every time Asynctask is called.

*

*Is it possible to avoid showing this when data was loaded so fast?

*Is thread.sleep recommended in this?

*Or a progressbar is not needed even loading 500 and above records?

Here's my code:
public void refreshList(String status) {
    String id = String.valueOf(getArguments().getInt("ID"));

    String paramsValue[] = new String[2];
    paramsValue[0] = id;
    paramsValue[1] = status;
    new LogsTask(this).execute(paramsValue);

}

private static class LogsTask extends AsyncTask<String[], Integer, LinkedHashMap<Integer, ValuesExtension>> {
    String paramsValue[];

    LogsFragment logsFragment;
    WeakReference<LogsFragment> fragmentWeakReference;

    LogsTask(LogsFragment logsFragment) {
        fragmentWeakReference = new WeakReference<>(logsFragment);
    }

    @Override
    protected void onPreExecute() {
        logsFragment = fragmentWeakReference.get();
        logsFragment.pbLogs.setVisibility(View.VISIBLE);
    }

    @Override
    protected LinkedHashMap<Integer, ValuesExtension> doInBackground(String[]... params) {
        Cursor dbReader = null;

        DBHelper dbHelper = new DBHelper(logsFragment.getContext());
        LinkedHashMap<Integer, ValuesExtension> logsMap = new LinkedHashMap<>();

        try {
            dbHelper.open();

            if (dbReader.getCount() > 0) {
                while (dbReader.moveToNext()) {
                    try {
                        /* LOADING OF DATA */
                        logsMap.put("values", value);

                        Thread.sleep(250); // is this important when loading data?
                    } catch (InterruptedException | ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (SQLException e) {
            return null;
        } finally {
            if (dbReader != null) {
                dbReader.close();
            }
            dbHelper.close();
        }
        return logsMap;
    }

    @Override
    protected void onPostExecute(LinkedHashMap<Integer, ValuesExtension> logsMap) {
        logsFragment.pbLogs.setVisibility(View.GONE);

        if (logsMap != null) {
            logsFragment.refreshLog();
        }

    }
}

A: As a work around, you can delay the start of progress bar for 300 milliseconds depending on how fast your data is loading
private boolean completed = false;
@Override
    protected void onPreExecute() {
        logsFragment = fragmentWeakReference.get();
        //below code won't display progress if your task completes within 300 ms and longer tasks it will be shown after 300 ms
        logsFragment.pbLogs.postDelayed(new Runnable(){
          @Override
          public void run(){
               if(!completed)
               logsFragment.pbLogs.setVisibility(View.VISIBLE);
         }, 300);
    }

 @Override
    protected void onPostExecute(LinkedHashMap<Integer, ValuesExtension> logsMap) {
        completed = true;
        logsFragment.pbLogs.setVisibility(View.GONE);

        if (logsMap != null) {
            logsFragment.refreshLog();
        }

    }


text:
Q: OOP: inheritance with recursive class definition I have (recursively) defined a class for implementing a binary tree (in Java):
class BinaryTree {
    protected int key;
    protected BinaryTree left, right;

    // some methods...
}

from which I want to implement a binary search tree, like this:
class BinarySearchTree extends BinaryTree {
    // ...

    public BinarySearchTree search(int x) {
        if (x == key)
            return this;
        if (x < key)
            if (left != null)
                return left.search(x);  // (*)
        else
            if (right != null)
                return right.search(x); // (*)
        return null;
    }
}

but of course the lines marked with // (*) won't compile beacause left and right are just BinaryTrees, without any search() method.
So I am wondering if theres is a way to define BinarySearchTree from the BinaryTree superclass but with left and right being actually BinarySearchTrees.
Or maybe there is a better way of implementing the relationship between binary trees and the search ones: should I define a separate Node class? should I use templates? should I avoid recursive definitions at all? ...

A: You can use recursive generics.
Define a recursive generic type variable, say, B:
class BinaryTree<B extends BinaryTree<B>> {

and make your fields of this type:
protected B left, right;

Then define:
class BinarySearchTree extends BinaryTree<BinarySearchTree> {

Now left and right are of type BinarySearchTree too, allowing you to call left.search and right.search.

A: I feel BinaryTreeNode should be created as an inner class ofBinaryTree.java. BinaryTreeNode can have int data, and two references of type BinaryTreeNode for left and right node
BinaryTree.java should have an reference of type BinaryTreeNode which will be the root of the tree.
Now BinarySearchTree extends BinaryTree looks good, you can include an method in it as below signature.
BinaryTreeNode `search( int k, BinaryTreeNode root)`

Now you can define the recursive method.
Please see Sample code with basic skeleton.
BinaryTreeNode.java
public class BinaryTreeNode {

    private int data;
    private BinaryTreeNode left, right;

    public BinaryTreeNode(int data) {
        this.setData(data);
    }

    public BinaryTreeNode getLeft() {
        return left;
    }

    public void setLeft(BinaryTreeNode left) {
        this.left = left;
    }

    public BinaryTreeNode getRight() {
        return right;
    }

    public void setRight(BinaryTreeNode right) {
        this.right = right;
    }

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

}

BinaryTree.java
public class BinaryTree {
    protected BinaryTreeNode root;

    // other basic methods needed for creating the Binary tree.
}

BinarySearchTree.java
public class BinarySearchTree extends BinaryTree {
    public BinaryTreeNode search(int k) {
        return search(k, root);
    }

    private BinaryTreeNode search(int k, BinaryTreeNode root) {
        if (root.getData() == k) {
            return root;
        }
        if (root.getData() < k) {
            return search(k, root.getRight());
        } else {
            return search(k, root.getLeft());
        }
    }
    // add other methods needed for creating the Binary search tree.
    // also override the methods which needs to be modified for their behavior
    // for binary search tree
}


text:
Q: How the Look-ahead and Look-behind concept supports such Zero-Width Assertions concept in Regex of Ruby? I just gone through the concept Zero-Width Assertions from the documentation. And some quick questions comes into my mind-

*

*why such name Zero-Width Assertions?

*How the Look-ahead and look-behind concept supports such
Zero-Width Assertions concept?

*What such ?<=s,<!s,=s,<=s - 4 symbols are instructing inside the pattern? can you help me here to focus to understand what is actually going on
I also tried some tiny codes to understand the logic, but not that much confident with the output of those:
irb(main):001:0> "foresight".sub(/(?!s)ight/, 'ee')
=> "foresee"
irb(main):002:0> "foresight".sub(/(?=s)ight/, 'ee')
=> "foresight"
irb(main):003:0> "foresight".sub(/(?<=s)ight/, 'ee')
=> "foresee"
irb(main):004:0> "foresight".sub(/(?<!s)ight/, 'ee')
=> "foresight"

Can anyone help me here to understand?
EDIT
Here i have tried two snippets one with "Zero-Width Assertions" concepts as below:
irb(main):002:0> "foresight".sub(/(?!s)ight/, 'ee')
=> "foresee"

and the other is without "Zero-Width Assertions" concepts as below:
irb(main):003:0> "foresight".sub(/ight/, 'ee')
=> "foresee"

Both the above produces same output,now internally how the both regexp move by their own to produce output- could you help me to visualize?
Thanks

A: Zero-width assertions are difficult to understand until you realize that regex matches positions as well as characters.
When you see the string "foo" you naturally read three characters. But, there are also four positions, marked here by pipes: "|f|o|o|". A lookahead or lookbehind (aka lookarounds) match a position where the character before or after match the expression.
The difference between a zero-width expression and other expressions is that the zero-width expression only matches (or "consumes") the position. So, for example:
/(app)apple/

will fail to match "apple" because it's trying to match "app" twice. But
/(?=app)apple/

will succeed because the lookahead is only matching the position where "app" follows. It doesn't actually match the "app" character, allowing the next expression to consume them.
LOOKAROUND DESCRIPTIONS

Positive Lookahead: (?=s)

Imagine you are a drill sergeant and you are performing an inspection. You begin at the front of the line with the intention of walking past each private and ensuring they meet expectations. But, before doing so, you look ahead one by one to make sure they have lined up in the property order. The privates' names are "A", "B", "C", "D" and "E". /(?=ABCDE)...../.match('ABCDE'). Yep, they are all present and accounted for.

Negative Lookahead: (?!s)

You perform the inspection down the line and are finally standing at private D. Now you are going to look ahead to make sure that "F" from the other company has not, yet again, accidentally slipped into the wrong formation. /.....(?!F)/.match('ABCDE'). Nope, he hasn't slipped in this time, so all is well.

Positive Lookbehind: (?<=s)

After completing the inspection, the sergeant is at the end of the formation. He turns and scans back to make sure no one has snuck away. /.....(?<=ABCDE)/.match('ABCDE'). Yep, everyone is present and accounted for.

Negative Lookbehind: (?<!s)

Finally, the drill sergeant takes one last look to make sure that privates A and B have not, once again, switched places (because they like KP). /.....(?<!BACDE)/.match('ABCDE'). Nope, they haven't, so all is well.

A: The meaning of a zero-width assertion is an expression that consumes zero characters while matching. For example, in this example,
"foresight".sub(/sight/, 'ee')

what is matched is
foresight
    ^^^^^

and thus the result would be
foreee

However, in this example,
"foresight".sub(/(?<=s)ight/, 'ee')

what is matched is
foresight
     ^^^^

and therefore the result would be
foresee

Another example of a zero-width assertion is the word-boundary character, \b. For example, to match a complete word, you might try surrounding the word with spaces, e.g.
"flight light plight".sub(/\slight\s/, 'dark')

to get
flightdarkplight

But you see how matching the spaces removes it during substitution? Using a word boundary gets around this problem:
"flight light plight".sub(/\blight\b/, 'dark')

The \b matches the beginning or end of a word, but does not actually match a character: it's zero-width.
Maybe the most succinct answer to your question is this: Lookahead and lookbehind assertions are one kind of zero-width assertions. All lookahead and lookbehind assertions are zero-width assertions.

Here are explanations of your examples:
irb(main):001:0> "foresight".sub(/(?!s)ight/, 'ee')
=> "foresee"

Above, you're saying, "Match where the next character is not an s, and then an i." This is always true for an i, since an i is never an s, so the substitution succeeds.
irb(main):002:0> "foresight".sub(/(?=s)ight/, 'ee')
=> "foresight"

Above, you're saying, "Match where the next character is an s, and then an i." This is never true, since an i is never an s, so the substitution fails.
irb(main):003:0> "foresight".sub(/(?<=s)ight/, 'ee')
=> "foresee"

Above, already explained. (This is the correct one.)
irb(main):004:0> "foresight".sub(/(?<!s)ight/, 'ee')
=> "foresight"

Above, should be clear by now. In this case, "firefight" would substitute to "firefee", but not "foresight" to "foresee".

A: Regular expressions match from left to right, and move a sort of "cursor" along the string as they go.  If your regex contains a regular character like a, this means: "if there's a letter a in front of the cursor, move the cursor ahead one character, and keep going.  Otherwise, something's wrong; back up and try something else."  So you might say that a has a "width" of one character.
A "zero-width assertion" is just that: it asserts something about the string (i.e., doesn't match if some condition doesn't hold), but it doesn't move the cursor forwards, because its "width" is zero.
You're probably already familiar with some simpler zero-width assertions, like ^ and $.  These match the start and end of a string.  If the cursor isn't at the start or end when it sees those symbols, the regex engine will fail, back up, and try something else.  But they don't actually move the cursor forwards, because they don't match characters; they only check where the cursor is.
Lookahead and lookbehind work the same way.  When the regex engine tries to match them, it checks around the cursor to see if the right pattern is ahead of or behind it, but in case of a match, it doesn't move the cursor.
Consider:
/(?=foo)foo/.match 'foo'

This will match!  The regex engine goes like this:

*

*Start at the beginning of the string: |foo.

*The first part of the regex is (?=foo).  This means: only match if foo appears after the cursor.  Does it?  Well, yes, so we can proceed.  But the cursor doesn't move, because this is zero-width.  We still have |foo.

*Next is f.  Is there an f in front of the cursor?  Yes, so proceed, and move the cursor past the f: f|oo.

*Next is o.  Is there an o in front of the cursor?  Yes, so proceed, and move the cursor past the o: fo|o.

*Same thing again, bringing us to foo|.

*We reached the end of the regex, and nothing failed, so the pattern matches.

On your four assertions in particular:

*

*(?=...) is "lookahead"; it asserts that ... does appear after the cursor.
1.9.3p125 :002 > 'jump june'.gsub(/ju(?=m)/, 'slu')
 => "slump june"

The "ju" in "jump" matches because an "m" comes next.  But the "ju" in "june" doesn't have an "m" next, so it's left alone.
Since it doesn't move the cursor, you have to be careful when putting anything after it.  (?=a)b will never match anything, because it checks that the next character is a, then also checks that the same character is b, which is impossible.

*(?<=...) is "lookbehind"; it asserts that ... does appear before the cursor.
1.9.3p125 :002 > 'four flour'.gsub(/(?<=f)our/, 'ive')
 => "five flour"

The "our" in "four" matches because there's an "f" immediately before it, but the "our" in "flour" has an "l" immediately before it so it doesn't match.
Like above, you have to be careful with what you put before it.  a(?<=b) will never match, because it checks that the next character is a, moves the cursor, then checks that the previous character was b.

*(?!...) is "negative lookahead"; it asserts that ... does not appear after the cursor.
1.9.3p125 :003 > 'child children'.gsub(/child(?!ren)/, 'kid')
 => "kid children"

"child" matches, because what comes next is a space, not "ren".  "children" doesn't.
This is probably the one I get the most use out of; finely controlling what can't come next comes in handy.

*(?<!...) is "negative lookbehind"; it asserts that ... does not appear before the cursor.
1.9.3p125 :004 > 'foot root'.gsub(/(?<!r)oot/, 'eet')
 => "feet root"

The "oot" in "foot" is fine, since there's no "r" before it.  The "oot" in "root" clearly has an "r".
As an additional restriction, most regex engines require that ... has a fixed length in this case.  So you can't use ?, +, *, or {n,m}.
You can also nest these and otherwise do all kinds of crazy things.  I use them mainly for one-offs I know I'll never have to maintain, so I don't have any great examples of real-world applications handy; honestly, they're weird enough that you should try to do what you want some other way first.  :)

Afterthought: The syntax comes from Perl regular expressions, which used (? followed by various symbols for a lot of extended syntax because ? on its own is invalid.  So <= doesn't mean anything by itself; (?<= is one entire token, meaning "this is the start of a lookbehind".  It's like how += and ++ are separate operators, even though they both start with +.
They're easy to remember, though: = indicates looking forwards (or, really, "here"), < indicates looking backwards, and ! has its traditional meaning of "not".

Regarding your later examples:
irb(main):002:0> "foresight".sub(/(?!s)ight/, 'ee')
=> "foresee"

irb(main):003:0> "foresight".sub(/ight/, 'ee')
=> "foresee"

Yes, these produce the same output.  This is that tricky bit with using lookahead:

*

*The regex engine has tried some things, but they haven't worked, and now it's at fores|ight.

*It checks (?!s).  Is the character after the cursor s?  No, it's i!  So that part matches and the matching continues, but the cursor doesn't move, and we still have fores|ight.

*It checks ight.  Does ight come after the cursor?  Well, yes, it does, so move the cursor: foresight|.

*We're done!

The cursor moved over the substring ight, so that's the full match, and that's what gets replaced.
Doing (?!a)b is useless, since you're saying: the next character must not be a, and it must be b.  But that's the same as just matching b!
This can be useful sometimes, but you need a more complex pattern: for example, (?!3)\d will match any digit that isn't a 3.
This is what you want:
1.9.3p125 :001 > "foresight".sub(/(?<!s)ight/, 'ee')
 => "foresight"

This asserts that s doesn't come before ight.


text:
Q: Determine a linear application How can I determine a linear application $f: \mathbb{R}^2 \to \mathbb{R}^2 $ such that $Kerf = span[ (-1, -5) $?
By the definition of Ker, we know that $ kerf = [ (x,y) \in \mathbb{R}^2 : f(x,y) = (0,0)] $. That is, we need to find a linear application such that f applied in the vectors that are linear combination of the vectors that form one basis of the kernel, we will have the 0 vector. But is there a method to find one application like this? I need a hint, probably I'm not seeing the best way to determine one application
Thanks!

A: Hint: try to find a linear map $\Bbb R^2\to\Bbb R$ with that kernel. Then to make an example $\Bbb R^2\to\Bbb R^2$, you can compose with a (almost any) linear map $\Bbb R\to\Bbb R^2$ so that the composition has the same kernel.


text:
Q: Semantic UI React progress bar with file upload I have a small file upload component where the user picks a file from their file system and uploads it (sent via REST call).
I'm trying to implement <Progress> module from semantic-ui-react to indicate success/failure when the file is sent to the endpoint. So is it best to do this based off the status of the response? Or is there a better way to handle it?
Codesandbox is here
    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          file: null,
          fileName: "",
          isUploading: false,
          statusCode: ""
        };
      }

      onFormSubmit = e => {
        e.preventDefault(); // Stop form submit
        this.fileUpload(this.state.file).then(response => {
          console.log(response.data);
        });
      };

      fileChange = e => {
        this.setState(
          { file: e.target.files[0], fileName: e.target.files[0].name },
          () => {
            console.log(
              "File chosen --->",
              this.state.file,
              console.log("File name  --->", this.state.fileName)
            );
          }
        );
      };

  fileUpload = async file => {
    const formData = new FormData();
    formData.append("file", file);
    try {
      axios.post("/file/upload/enpoint").then(response => {
        console.log(response);
        console.log(response.status);
        this.setState({ statusCode: response.status }, () => {
          console.log(
            "This is the response status code --->",
            this.state.statusCode
          );
        });
      });
    } catch (error) {
      console.error(Error(`Error uploading file ${error.message}`));
    }

    const data = JSON.stringify({
      uploadData: file
    });
    console.log(data);
  };

  render() {
    const { statusCode } = this.state;
    const panes = [
      {
        menuItem: "Import ",
        render: () => (
          <Tab.Pane attached={false}>
            <Message>Some random message idk.</Message>
            <Form onSubmit={this.onFormSubmit}>
              <Form.Field>
                <label>File input & upload </label>
                <Button as="label" htmlFor="file" type="button" animated="fade">
                  <Button.Content visible>
                    <Icon name="file" />
                  </Button.Content>
                  <Button.Content hidden>Choose a File</Button.Content>
                </Button>
                <input
                  type="file"
                  id="file"
                  hidden
                  onChange={this.fileChange}
                />
                <Form.Input
                  fluid
                  label="File Chosen: "
                  placeholder="Use the above bar to browse your file system"
                  readOnly
                  value={this.state.fileName}
                />
                <Button style={{ marginTop: "20px" }} type="submit">
                  Upload
                </Button>
                {statusCode && statusCode === "200" ? (
                  <Progress
                    style={{ marginTop: "20px" }}
                    percent={100}
                    success
                    active
                    progress
                  />
                ) : statusCode && statusCode === "500" ? (
                  <Progress
                    style={{ marginTop: "20px" }}
                    percent={100}
                    error
                    active
                    progress
                  />
                ) : null}
              </Form.Field>
                </Form>
              </Tab.Pane>
            )
          }
        ];
        return (
          <Segment style={{ padding: "5em 1em" }} vertical>
            <Divider horizontal>OFFLINE USAGE</Divider>
            <Tab menu={{ pointing: true }} panes={panes} />
          </Segment>
        );
      }
    }

A: I have a proposed solution that is mainly focused on the reducers. What you have to do is you have to dispatch a loading action.
Go to my Github repo: Semantic UI Indicator
You would be able to go through the repo and understand that. This is just a different method. So there can be many ways to do that. I have used a simple semantic loader in case you can apply the same thing to the progress bar.

A: I changed the fileUpload function to update a statusCode state variable with the response.status from the server response.
  fileUpload = async file => {
    const formData = new FormData();
    formData.append("file", file);
    try {
      axios.post("/file/upload/enpoint").then(response => {
        console.log(response);
        console.log(response.status);
        this.setState({ statusCode: response.status }, () => {
          console.log(
            "This is the response status code --->",
            this.state.statusCode
          );
        });
      });
    } catch (error) {
      console.error(Error(`Error uploading file ${error.message}`));
    }
  };

Then in render I checked for the statusCode to be either 200 or 500, I will change it to include more appropriate status codes but you get the idea.
{statusCode && statusCode === 200 ? (
                  <Progress
                    style={{ marginTop: "20px" }}
                    percent={100}
                    success
                    progress
                  >
                    File Upload Success
                  </Progress>
                ) : statusCode && statusCode === 500 ? (
                  <Progress
                    style={{ marginTop: "20px" }}
                    percent={100}
                    error
                    active
                    progress
                  >
                    File Upload Failed
                  </Progress>
                ) : null}

The updated codesandbox can be found here for those who want to take a look.


text:
Q: Firebase - get user based on date I have a User model which contain a field:
var created_on: Double?

and when the user signs up it gets assigned:
Date().timeIntervalSince1970

and i want to get the users who joined today, at the moment i have something like:
Firestore.firestore().collection("users")
      .whereField("activated", isEqualTo: 1)
      .whereField("city", isEqualTo: loggedInUser.city)
      .getDocuments{(snapshot, error) in
      guard let snap = snapshot else {
          return
      }

Im trying to have something like this (pseudo):
.whereField("created_on", isEqualTo: today)

A: Since you storing timestamp, your query actually is selecting a range:
.whereField("created_on", isGreaterThanOrEqualTo: startOfToday)
.whereField("created_on", isLessThan: startOfTomorrow)

Where startOfToday and startOfTomorrow are the TimeInterval/Double values for the start of today and tomorrow respectively.


text:
Q: Vertically fixed slider to content below I have an image slider on top of my website. It's here on my hosting page with top slider
I need to fix this slider vertically, so bottom content will scroll above my slider. When slider will stay like fixed block.
I have the same example with image, this is the same page but instead of slider here is block with background image, and fixed background-attachment the same page with background image on top
So in second link you can see effect what I want to apply with slider. Is it possible? I can't find way.

A: Add this to your current css and it should have the effect you're seeking.
.slider-bg {
 position: relative;
 z-index: -1;
 height: 502px;
}

.flexslider {
 position: fixed;
}

You need to set color for your .container as well or create a new class/id name for all your sections (ie your .container) and apply a background color to it.
Updated
Since your slider have a buttons, setting its z-index to -1 would make the buttons unclickable, you need to set you .slider-bg z-index to 1 and your
.container {
  position: relative;
  z-index: 2;
  background-color: #fff;
}

A: I guess you want Carousel. The Carousel plugin is a component for cycling through elements, like a carousel (slideshow).
Tip: Plugins can be included individually (using Bootstrap's individual "carousel.js" file), or all at once (using "bootstrap.js" or "bootstrap.min.js").
Sample Code :
<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

If you want more information in simplified way please visit this


text:
Q: c program SWIG to python gives 'ImportError: dynamic module does not define init function' I am trying to use .c program in python script with SWIG. To start with, I installed SWIG and trying simple example from tutorial swig webpage.
I am using Raspberry Pi with Raspbian GNU/Linux 9.4 (stretch)
This is what I do:
1. swig -python example.i - great, this created two new files: 'example.py' and 'example_wrap.c'
2. gcc -fpic -I/usr/include/python2.7 -c example_wrap.c - this creates 'example_wrap.o' file
3. compile example.c in Geany; this gives 'example.o' file
4. gcc -shared example.o example_wrap.o -o example.so - now a new file 'example.so' is created.
Time to try it:
python

I am using Python 2.7.13 here
>>>import example

And this gives traceback:
File "<stdin>", line 1, in <module>
ImportError: dynamic module does not define init function (initexample)

How to sort this problem out?

A: This is what happens for a dynamic Python module (at least, in current swig version):

*

*The module name (let's stick with example, like in the tutorial) is specified in the .i file: %module example

*At build time, 2 files are generated:

*

*_${MODULE_NAME}.so: a dynamic module or shared object having the name the module name preceded by an UnderScore, in our example _example.so, which contain the actual C compiled code

*${MODULE_NAME}.py: which is a wrapper over the previous one; example.py - this is the module "entry point"
A Python dynamic module must export an init* function (PyInit_* in Python 3) as explained on [Python 2.Docs]: The Module's Method Table and Initialization Function, and more: what comes after the init part, must match module (.so) name (in our case it's init_example).
By naming the dynamic module example.so, when Python tried to load it, it searched for initexample which (obviously) didn't exist, raising ImportError.
Changing the module name to _example.so (gcc -shared example.o example_wrap.o -o _example.so), as the URL also instructs, no longer raises an exception.
Then, the functions are available like this:

>>> import example  # This imports example.py which automatically imports _example.so
>>> example.fact(4), example.my_mod(7, 2), example.get_time()

Might also want to check:

*

*[SO]: How to solve Python-C-API error "This is an issue with the package mentioned above, not pip."? (@CristiFati's answer)

A: Like CristiFati said "gcc -shared example.o example_wrap.o -o _example.so"
The naming is wrong and causing the error.


text:
Q: How can 2-adic valuations be enhanced to accommodate a sixth root of unity? Let $f:\Bbb N^+\to\Bbb N^+/\langle2,3\rangle(\phi)$ replace the powers of $2$ and $3$ in the prime factorisation of any given positive integer with some number of the form $2^n\phi:n\in\Bbb N$, where $\phi$ is a sixth root of unity.
I've been using functions on the domain which use the 2-adic valuation and I want to define new functions on the range which use a new valuation that takes account of the roots of unity.  Is there a natural such valuation* that extends the 2-adic value?
*Note I'm aware this isn't a field therefore this isn't technically a valuation but I used the word anyway as it's a subset of fields and I think it's clear what it means.


text:
Q: Running Background Loop while Taking in Input (C++) I am currently working on developing a simple game, but I am getting quite stumped with one of the core mechanics. I want to be able to run a background loop that updates information (such as currency, location, etc.) every second or so. However, I want the user to be able to input actions at any moment without interrupting the loop. These actions will then change the way the background loop is updating info. My most recent attempt at this was to have two threads running simultaneously. One which will run the background clock and one which will constantly be open to input and react appropriately. However, I found it difficult for the input thread to affect the background thread. They were both just running in there own little world.
Any ideas as to how to approach this issue? Is multi-threading the right approach? Any help would be appreciated :). I can show some of my code if need be.

A: Simple method: Update the information right after user makes any changes if the update procedure is not taking too much time. This way you don't need multi-threading. Basic idea, if there is a changes then update.
Advance method: You will have 2 thread. First thread receives the action from the user, queue it. The second thread read the action in the queue and update information according to the action.
Looking like this:
INPUT thread -> [up,down,...,left,right,up] -> UPDATE thread
You can easily google the solution because this type of problem is pretty 'classic'.

A: The are a lot of ways to share information between threads.  This is just an example.  You can also global scope or IPC messaging.
#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread/thread.hpp>

using namespace std;
using namespace boost::posix_time;

typedef struct program_data_t {
    program_data_t() : counter(0) { }

    int counter;
    boost::mutex mutex;
} program_data_t;

void update_loop(program_data_t* pd) {
    while(1) {
        boost::this_thread::sleep(milliseconds(50));

        boost::mutex::scoped_lock(pd->mutex);

        pd->counter++;
    }
}

void print_loop(program_data_t* pd) {
    while(1) {
        boost::this_thread::sleep(seconds(1));

        boost::mutex::scoped_lock(pd->mutex);

        cout << pd->counter << endl;
    }
}

int main() {
    program_data_t pd;

    boost::thread update_thread(boost::bind(update_loop, &pd));
    boost::thread print_thread(boost::bind(print_loop, &pd));

    update_thread.join();
    print_thread.join();

    return 0;
}


text:
Q: Specifying root folder express-http-proxy I am using express-http-proxy
basic setup
const express = require('express');
const proxy = require('express-http-proxy');

app.use('/api/', proxy(`http://api-url/`));

app.listen(3000);

works as expected, except static files. they are point to proxy host instead of proxy route
http://localhost:3000/bundle.js

it should be
http://localhost:3000/api/bundle.js

A: I am assuming that bundle.js is a file hosted on the proxy host. Wherever it is referenced you may have to use relative paths so that it does not go to the root of the url.


text:
Q: How to translate this expr from pinescript v2 to v5 I´m trying to recode expr to Pinescript v5 but doesn't work same way, any idea?
Pinescript v2:
MA2 = nz(MA2[1]) + smooth * (hlc3 - nz(MA2[1]))
Pinescript v5:
float nAMA = 0.
MA := nz(MA[1]) + smooth * (hlc3 - nz(MA[1]))

A: Replace
float nAMA = 0.
By
float MA = 0.


text:
Q: mat dialog to open only in active component in landing component i have 2 components side by side.
say ComponentA, ComponentB
if i open mat -dialog from Component A, mat dialog should overlay in component A only not in parent component, Please help

        Forgot Password?

ForgotPassword(){
    console.log("open")
    const dialogConfig = new MatDialogConfig();
    dialogConfig.autoFocus = true;
    const dialogRef = this.dialog.open(ForgotPasswordDialogComponent, dialogConfig);
  }


text:
Q: Combining two different strings in a map I've been trying out the new section on codingbat, map1 & 2. I've finished map1, and I'm halfway through map2 but I'm just stuck on this one problem. I can't seem to figure out how to combine two strings.

Given an array of non-empty strings, return a Map<String, String>
  with a key for every different first character seen, with the value of
  all the strings starting with that character appended together in the
  order they appear in the array.

Examples:
firstChar(["salt", "tea", "soda", "toast"]) → {"t": "teatoast", "s": "saltsoda"}
firstChar(["aa", "bb", "cc", "aAA", "cCC", "d"]) → {"d": "d", "b": "bb", "c": "cccCC", "a": "aaaAA"}
firstChar([]) → {}

Here's my code:
public Map<String, String> firstChar(String[] strings)
{
  Map<String, String> map = new HashMap<String, String>();
  String x = "";
   for ( String s: strings )
     {
      if ( s.substring(0,1) == s.substring(0,1))
       x += s;
         map.put(s.substring(0,1), x);
     }
  return map;
}

I only get {"d": "d", "b": "", "c": "", "a": ""}
I've also tried s.substring(0, 1, map.get(s) + map.get(s)) which only returns null. If anyone could explain this to me it would be greatly appreciated!
Thank you !

A: Your logic is wrong, you are comparing the first character of the string with itself. Also, although it is not diretly your problem here, you are comparing strings with == instead of equals. == is used to compare references, equals is used to compare logical equality. Plus, for getting the first character of a string you can just use s.charAt(0). Ironically, you would not have had this issue if you had done it because String.charAt returns a char, which is a primitive type and thus can be compared safely using ==.
Code with various improvements and fixes:
public Map<String, String> firstChar(String[] strings) {
  Map<String, String> map = new HashMap<>();
  for (String s: strings) {
     map.merge(String.valueOf(s.charAt(0), s, String::concat);
  }
  return map;
}

Or pre-Java 8:
public Map<String, String> firstChar(String[] strings) {
  Map<String, String> map = new HashMap<>();
  for (String s: strings) {
     String key   = String.valueOf(s.charAt(0));
     String value = map.get(key);
     map.put(key, (value == null ? "" : value) + s);
  }
  return map;
}

A: public Map<String, String> firstChar(String[] strings) {
Map<String, String> map = new HashMap<String, String> ();
  for (String s:strings) {
  if (!map.containsKey(s.substring(0,1))) {  // first time we've seen this string
      map.put(s.substring(0,1), s);

  }
  else
  {
     String existing = map.get(s.substring(0,1));
      map.put(s.substring(0,1), existing+s);
  }

}
  return map;
}

A: public Map<String, String> firstChar(String[] strings) {
    Map<String, String> map = new HashMap<String, String>(strings.length);
    for (String string : strings) {
        String firstCharacter = String.valueOf(string.charAt(0));
        map.put(firstCharacter, map.getOrDefault(firstCharacter, "") + string);
    }
    return map;
}

A: public Map<String, String> firstChar(String[] strings) {
    Map<String, String> str = new HashMap<String, String>();
    for (int i = 0; i < strings.length; i++) {
        String value = "";
        for (int j = 0; j < strings.length; j++) {
            if (strings[i].charAt(0) == strings[j].charAt(0)) {
                value = value+strings[j];
            }
        }
        str.put(Character.toString(strings[i].charAt(0)), value);
    }
    return str;
}


text:
Q: If $L_A:(\mathbb{R}^2, \| \cdot \|_p) \to (\mathbb{R}^3, \| \cdot \|_p )$ is an isometry, is set of columns of $A$ orthonormal? Let $p\in [1,\infty)$.
Given a $3\times 2$ matrix $A$, let $L_A:(\mathbb{R}^2, \| \cdot \|_p) \to (\mathbb{R}^3, \| \cdot \|_p )$ be an operator defined by $L_A(z) = Az$.

Question: If $L_A$ is an isometry, does it mean that the set of columns of $A$ form an orthonormal set?

Since $L_A$ is an isometry, by considering $L_A(1,0)^T$ and $L_A(0,1)^T$, clearly the set of columns of $A$ has norm $1$.
However, I am not able to prove that they are orthogonal.
Clearly the question has positive answer if $p=2$ as one can use inner product induced by the norm $\|\cdot\|_2$ to show that the columns of $A$ are orthogonal.
It would be good if there is a reference for this fact, if it is true.

Remark: Let $(a_{11},a_{21}, a_{31})^T, (a_{12},a_{22}, a_{32})^T$ be the two columns of $A$.
We say that $\{(a_{11},a_{21}, a_{31})^T, (a_{12},a_{22}, a_{32})^T\}$ is orthonormal if $\|(a_{11},a_{21}, a_{31})\|_p = \|(a_{12},a_{22}, a_{32})\|_p = 1$ and $a_{11}a_{12} + a_{21}a_{22} + a_{31}a_{32}= 0$.


text:
Q: Getting Job Id in a Laravel queue with Database driver I have a laravel job which I create from a controller and some times i want to delete those jobs as the timings will be rescheduled
It is a notification job which sends notification one hour before a class and if the class is rescheduled i need to delete the jobs and insert new ones
my controller code is as below
$job = (new OnlineClassRemainderJob($remainder_data))->delay($value);
$id = dispatch($job);
array_push($job_ids, $id);

and the Job class is as shown below
<?php

namespace App\Jobs;

use App\Mail\OnlineClassRemainderMail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Mail;

class OnlineClassRemainderJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $details;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($details)
{
$this->details = $details;

}

/**
* Execute the job.
*
* @return void
*/
public function handle()
{

Mail::to($this->details['email'])
->send(new OnlineClassRemainderMail($this->details));

}
}

Kindly show light how I can get the Job id so that i can save it in a database and in case of a reschedule i can remove all job ids related to that class and then dispatch new schedules
I can layout the scenario here
I am scheduling classes for example
I have a class on every day from 20th Jan to 25th Jan at 10 AM and I am scheduling a remainder mail sending job which will fire 1 hour before the class
But at certains scenario the Classes will be rescheduled and for that purpose i need to reschedule the remainders or delete and redispatch the jobs

A: you need to retrun job id from job with this function $this->job->getJobId();
class OnlineClassRemainderJob implements ShouldQueue
{
     use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
       Mail::to($this->details['email'])
               ->send(new OnlineClassRemainderMail($this->details));
       retrun $this->job->getJobId();
    }
}

then
$job = (new OnlineClassRemainderJob($remainder_data))->delay($value);
$id = dispatch($job);
array_push($job_ids, $id);

ref link https://laravel.com/api/8.x/Illuminate/Contracts/Queue/Job.html#method_getJobId

A: To take the id of a job before executing it, e.g. to dequeue it before executing it.
$log = UpdateLog::create();
UpdateProduct::dispatch($log)->delay(now()->addMinutes(10));
$regex = 'UpdateLog.*?id\\\\";i:'.$log->id.';';
//delete or get job before start
DB::table('jobs')->where('payload','REGEXP',$regex)->delete();

my job example
//...
class UpdateProduct implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * @var UpdateLog
     */
    protected $log;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(UpdateLog $log)
    {
        $this->log = $log;
    }
//...
}


text:
Q: Customise train_step in model.fit() Tensorflow Keras - InvalidArgumentError: Operation 'while' has no attr named '_XlaCompile' I am trying to implement a custom multi-input and -output model which uses a learning algorithm as proposed in this paper. The model itself works fine without the custom learning algorithm which I use as a baseline. The problem I encounter is that the code got stuck in the train_step function in the DebiasModel class at code line:
mc_pred = self.main_classifier([xu, xs], training=True)

It did not return an error. After running for an hour, I interrupted the kernel and it returns the error message saying:
InvalidArgumentError: Operation 'while' has no attr named '_XlaCompile'.

During handling of the above exception, another exception occurred:

InvalidArgumentError: Operation 'gradients/while_grad/Placeholder_28' has no attr named '_read_only_resource_inputs'.

I am not sure what the issue is and I have tried to use persistent=True in tf.GradientTape as well instead of declaring two gradientTapes in single watch. But, exactly the same error occurs.
Does anyone have any idea what this issue is? And how it can be solved?
I am using Tensorflow V2.3.0 and Keras V2.4.0
Source Code
class model_components:

  def mitigation_expert():
    inputs = Input(shape=(300,), dtype=tf.int32, name="me_input")
    x = Embedding(num_tokens, 300, weights=[embedding_matrix], input_length=max_length, trainable=False, name="me_embedding")(inputs)
    x = LSTM(300, return_sequences=False, name="me_lstm")(x)

    model = Model(inputs, x)

    return model

  def control_expert():
    inputs = Input(shape=(22,), dtype=tf.int32, name="ce_input")
    y = Dense(19, activation='relu', name="ce_hidden")(inputs)

    model = Model(inputs, y)

    return model

  def main_classifier():
    # Expert components
    me = model_components.mitigation_expert()
    ce = model_components.control_expert()

    # Main classifier
    ensemble = concatenate([me.output, ce.output], name="pred_ensemble")
    pred_output = Dense(319, activation="relu", name="pred_hidden")(ensemble)
    pred_output = Dense(3, activation="softmax", name="pred_output")(pred_output)

    model = Model(inputs=[me.input, ce.input], outputs=pred_output, name="main_classifier")

    return model

  def adversary_classifier():
    # Mitigation Expert component
    me = model_components.mitigation_expert()

    # Adversary classifier
    adv_output = Dense(300, activation='relu', name="adv_hidden")(me.output)
    adv_output = Dense(1, activation='sigmoid', name="adv_output")(adv_output)

    model = Model(inputs=me.input, outputs=adv_output, name="adversary_classifier")

    return model

def tf_normalize(x):
  return x / (tf.norm(x) + np.finfo(np.float32).tiny)

class DebiasModel(keras.Model):
    def __init__(self, main_classifier, adversary_classifier):
        super(DebiasModel, self).__init__()
        self.main_classifier = main_classifier
        self.adversary_classifier = adversary_classifier

    def compile(self, mc_optimizer, adv_optimizer, mc_loss, adv_loss, debias_param):
        super(DebiasModel, self).compile()
        self.mc_optimizer = mc_optimizer
        self.adv_optimizer = adv_optimizer
        self.mc_loss = mc_loss
        self.adv_loss = adv_loss
        self.debias_param = debias_param

    def train_step(self, data):
      # Unpack data from model.fit()
      x, y, sample_weight = data

      # Unpack input and output features
      xu, xs = x
      y_mc = y['pred_output']
      z_adv = y['adv_output']

      # Unpack sample_weights
      mainClass_weights = sample_weight["pred_output"]
      protectClass_weights = sample_weight["adv_output"]

      # Generate prediction and compute loss for Main_Classifier
      with tf.GradientTape() as mc_tape, tf.GradientTape() as me_mc_tape:
        mc_pred = self.main_classifier([xu, xs], training=True)
        mc_loss = self.mc_loss(y_mc, mc_pred, sample_weight=mainClass_weights)

      # Compute and Apply Gradients for CE & Main Classifier
      mc_trainable_vars = self.main_classifier.trainable_weights[3:]
      mc_grads = mc_tape.gradient(mc_loss, mc_trainable_vars)
      self.mc_optimizer.apply_gradients(zip(mc_grads, mc_trainable_vars))

      # Generate prediction and compute loss for Adversary_Classifier
      with tf.GradientTape() as adv_tape, tf.GradientTape() as me_adv_tape:
        adv_pred = self.adversary_classifier(xu)
        adv_loss = self.adv_loss(z_adv, adv_pred, sample_weight=protectClass_weights)

      # Compute and Apply Gradients for CE & Main Classifier
      adv_trainable_vars = self.adversary_classifier.trainable_weights[3:]
      adv_grads = adv_tape.gradient(adv_loss, adv_trainable_vars)
      self.adv_optimizer.apply_gradients(zip(adv_grads, adv_trainable_vars))

      # Compute and Apply Gradients to debias ME
      me_adv_debias_trainable_vars = self.adversary_classifier.trainable_weights[:3]
      adv_debias_grads = me_adv_tape.gradient(adv_loss, me_adv_debias_trainable_vars)
      adv_debias_dict = tf.lookup.StaticHashTable(
          tf.lookup.KeyValueTensorInitializer(me_adv_debias_trainable_vars, adv_debias_grads), 0)

      me_mc_debias_trainable_vars = self.main_classifier.trainable_weights[:3]
      mc_debias_grads = me_mc_tape.gradient(mc_loss, me_mc_debias_trainable_vars)

      me_grads = []

      for g, v in zip(mc_debias_grads, me_mc_debias_trainable_vars):
        unit_adv = tf_normalize(adv_debias_dict.lookup(v))
        g -= tf.math.reduce_sum(g * unit_adv) * unit_adv
        g -= self.debias_param * adv_debias_dict.lookup(v)
        me_grads.append(zip(g, v))

      self.mc_optimizer.apply_gradients(me_grads)

      return {"pred_loss": mc_loss, "adv_loss": adv_loss}

model = DebiasModel(model_components.main_classifier(),
                    model_components.adversary_classifier())

model.compile(mc_optimizer=tf.keras.optimizers.Adam(),
              adv_optimizer=tf.keras.optimizers.Adam(),
              mc_loss=tf.keras.losses.CategoricalCrossentropy(),
              adv_loss=tf.keras.losses.BinaryCrossentropy(),
              debias_param=1)

epoch = 5
sample_weights = {
    "pred_output": mainClass_weight,
    "adv_output": protectClass_weight,}

model.fit(x=[xu_train, xs_train],
          y={"pred_output": y_train, "adv_output": z_train},
          validation_data=([xu_val, xs_val], {"pred_output": y_val, "adv_output": z_val}),
          sample_weight=sample_weights, epochs=epoch, batch_size=256, verbose=1)

Error Traceback
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py in get_attr(self, name)
   2485       with c_api_util.tf_buffer() as buf:
-> 2486         pywrap_tf_session.TF_OperationGetAttrValueProto(self._c_op, name, buf)
   2487         data = pywrap_tf_session.TF_GetBuffer(buf)

InvalidArgumentError: Operation 'while' has no attr named '_XlaCompile'.

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
51 frames
ValueError: Operation 'while' has no attr named '_XlaCompile'.

During handling of the above exception, another exception occurred:

InvalidArgumentError                      Traceback (most recent call last)
InvalidArgumentError: Operation 'gradients/while_grad/Placeholder_28' has no attr named '_read_only_resource_inputs'.

Note: I have not added the full traceback, but if needed I can provide it. Many thanks in advance!


text:
Q: matrix and vector multiplication python3 I am not able to get my desired output for my code. The problem I am having is that when I multiply matrix_0 and vector_0 I get the correct output, but for matrix_1 and vector_1 it is incorrect. As well as matrix_2 and vector_2. I am new to coding and the python3 language and don't understand why. Any help would be great. Thank you in advance. I have attached a link to my code.
code link
The following is my code snipper
def matVec(matrix,vector):
  result = []
  for i in range(len(matrix)):
    total = 0
    for j in range(len(vector)):
      total += matrix[i][j] * vector[j]
    result.append(total)
  return result
matrix_0 = [[1, 2],[2, 3]]
vector_0 = [8, 10]
matrix_1 = [[ 2, 2, 3]]
vector_1 = [2]
matrix_2 = [[3, 2],[4, 4],[1, 1]]
vector_2 = [1, 2, 3]
print(matVec(matrix_0,vector_0))

A: The shapes of matrix_2 and vector_2 are not aligned. Test your code against what numpy outputs.
import numpy as np

np.matmul(matrix_2, vector_2)

Out[ ]:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-10-752f945775e1> in <module>()
----> 1 np.matmul(matrix_2, vector_2)

ValueError: shapes (3,2) and (3,) not aligned: 2 (dim 1) != 3 (dim 0)

A: You will get an error or a wrong answer in _1 and _2. The reason for this problem is your matrixes and vectors can't be multipied. The amount of columns in the matrix has to be the same amount as the rows in the vector. Hope this helps, write a comment if there is something that needs a more thorough explanation.
Your code is really good


text:
Q: Factorization of Polynomials over a Field: Question on Theorem In Fraleigh's Abstract Algebra book this corollary is written and proven shortly after Gauss's lemma is introduced:
Corollary: If $f(x) = x^n + a_{n-1}x^{n-1} + \cdots + a_0$ is in $\mathbb{Z}[X]$ with $a_0 \neq 0$, and if $f(x)$ has a zero in $\mathbb{Q}$, then it has a zero $m$ in $\mathbb{Z}$ and $m$ must divide $a_0$.
Proof:
If $f(x)$ has a zero $a \in \mathbb{Q}$, then $f(x)$ has a linear factor $(x - a) \in \mathbb{Q}$, but then by Gauss's Lemma $f(x)$ also has a linear factorization in $\mathbb{Z}[X]$, so for some $m \in \mathbb{Z}$ we must have
$f(x) = (x - m)(x^{n-1} + \cdots - \frac{a_0}{m})$. Thus $a_0/m$ is in $\mathbb{Z}$, so $m$ divides $a_0$.
Now my question: From the Rational Root Thm since this is a monic polynomial, all the possible roots would have to be divisors of $a_0$, so the roots would always be in $\mathbb{Z}[X]$? Is this correct, if not can you show an example?


text:
Q: Facebook social graph still fetching old values and not the updated ones I made a new blog post on my website and provided an image for SocialGraph tag:
<meta property="og:image" content="http://i.imgur.com/someOldImage.jpg" />

The image was hosted on imgur, and posted it on the web.
After few minutes I decided to change the image and updated it to the new image that was also uploaded on the imgur. However as far as the html markup is concerned it does show social graph tag values according to the new image.
<meta property="og:image" content="http://i.imgur.com/someNewImage.jpg" />

But when I go to post on facebook the facebook preview shows the imgur error that
the image you request doesn't exists or no longer available

Which means that FB is still trying to fetch the old image and not the new one even though I have updated it in the markup?
Why is this so, how can I refresh facebook social graph values for the url? Please explain its an important post and this way its like causing an embarrassment?

A: Go to https://developers.facebook.com/tools/debug
Enter URL and append fbrefresh=CAN_BE_ANYTHING
Example: http://example.com/?fbrefresh=CAN_BE_ANYTHING


text:
Q: Ubuntu Server cron job doesn't work My script that is supposed to run only when the server is on isn't working correctly when run by cron. If I run it manually, it works.
backup() {
  if pidof java &> /dev/null; then

     screen -p 0 -S minecraft -X eval "stuff \"say server backing up\"\015"
     # We need to first put the server in readonly mode to reduce the chance of backing up half of a chunk.
     screen -p 0 -S minecraft -X eval "stuff \"save-off\"\015"
     screen -p 0 -S minecraft -X eval "stuff \"save-all\"\015"

     sleep 10

     cd ~/Minecraft
     mkdir backup
     tar cvfpz backup/Y-$(date +%Y_M-%m_D-%d_T-%H_%M)-world.backup.tar.gz world/

     screen -p 0 -S minecraft -X eval "stuff \"save-on\"\015"
     screen -p 0 -S minecraft -X eval "stuff \"say server done backing up\"\015"

     # Delete old backups
     echo deleting old backups
     find . -name '*-world.backup*' -mtime +5 -delete

   else
      echo Minecraft Server not on
   fi
 }

I'm wondering if anyone knows why it's not stopping the backup if the server is stopped?

A: What does the crontab file look like that is supposed to start that script?
And what are the permissions/owner of the script?
On this link I found:

*

*When cron job is run from the users crontab it is executed as that user. It does not however source any files in the user's home directory like their .cshrc or .bashrc or any other file. If you need cron to source (read) any file that your script will need you should do it from the script cron is calling. Setting paths, sourcing files, setting environment variables, etc.

*If the users account has a crontab but no usable shell in /etc/passwd then the cronjob will not run. You will have to give the account a shell for the crontab to run.

*If your cronjobs are not running check if the cron deamon is running. Then remember to check /etc/cron.allow and /etc/cron.deny files. If they exist then the user you want to be able to run jobs must be in /etc/cron.allow. You also might want to check if the /etc/security/access.conf file exists. You might need to add your user in there.

*Crontab is not parsed for environmental substitutions. You can not use things like $PATH, $HOME, or ~/sbin. You can set things like MAILTO= or PATH= and other environment variables the /bin/sh shell uses.

So, I'd start by editing the cronjob itself and changing the ~ to /home/popcorn9499.
Then do the same for the script.
Also in the script add #! /bin/bash as the first line.
If everything in the script is just the function backup() { take that line out and the final } and make it a plain bash script. You can then loose the backup argument and teh cronjob becomes: */30 * * * * /home/popcorn9499/Scripts/minecraft.sh
(you really need to make a backup every 30 minutes?)
Next, make sure you have rwx permission for the scriptfile: chmod u+rwx ~/Scripts/minecraft.sh
Finally, consider renaming your directory ~/Scripts to ~/bin as that is already in your $PATH.
That should fix things.


text:
Q: MdlSelect - ViewDestroyedError: Attempt to use a destroyed view: detectChanges I'm getting the same issue as mentioned in this
github issue
I'm using the following versions:
"@angular-mdl/core": "^8.0.0",
"@angular-mdl/popover": "^8.0.0",
"@angular-mdl/select": "^8.0.0",

From the issue, it seems that this was fixed in this PR and was published as @angular-mdl/select:0.11.2, but I don't see that fix in version 8.
Could you please help me out with a fix for this issue on "@angular-mdl/select": "^8.0.0"
Thanks in advance.


text:
Q: Best practice for displaying items in localStorage in html.erb file I have an array of items in localStorage that I want to display in my index.html.erb file. I'm using rails for this application. Should I send the information to my rails controller and then send it to my index.html.erb or is there a way to do it without sending the info to the controller? I rather not save the information on the server side.
Here's my code in my index.html.erb

Right now this is showing just one item in the array in the view page instead of a number of items. If I do have to send the information to the controller first, how would I go about doing that? Any feedback would be greatly appreciated.

A: You are replacing the html every iteration so only the last item will be shown
Try something like:
document.getElementById("result").innerHTML += (items[i] + '
`);

Note: This assumes you are actually storing an array


text: Q: Find all image in div of another page and insert to this page I want to get all the images in a div of another page and include them to current page. I tried this code but It's not working.


text:
Q: Max aggrigate query has huge cost against # query rows returned limit So I have a query:
AggregateResult[] results = [select max(Cash_Rewards_Number_Field__c) MaxName from Team__c];

This started causing 50001 too many rows returned errors in my trigger. When checking the debug logs, it seems as though it counted the total number of records in the team object against the query rows returned limit.
I also Tried:
List<Team__c> highestCashRewardTeam = [select Cash_Rewards_Number_Field__c from Team__c ORDER BY Cash_Rewards_Number_Field__c DESC LIMIT 1];

but the same problem arrises. Is there no way to get the max value from an object without the entirety of the objects table counting against the limit?

A: Based on comments:
Filtering, ordering by (even with LIMIT), or grouping by a formula field always results in a full table scan. This will result in 50,000+ row errors or non-selective filter errors (e.g. when more than 100,000 rows exist). When possible, copy the values to an indexed field (say, via workflow rules), or run the task asynchronously, such as in a Batchable class.


text:
Q: Tag Helpers not binding data when calling form submit via javascript So I've got a form. I'm utilizing tag helpers. The form only has one text input, and I'm trying to use the Bootstrap "input-group-addon" div as the submit button for this small form.
I'm running into strange behavior. If I just hit the enter key after typing something into the input, the data binds fine over into the controller action.
However, if I attach an onclick listener to the div, and run getElementById('Form').submit();, when I click the div, it still takes me to the controller action, but none of the data is bound to the incoming for model.
Razor form:
<form asp-controller="Search" asp-action="HomeBuyersSearchSubmit" id="Home_Buyers_Search_Form">

                    <input asp-for="Query" class="form-control" placeholder="City, Neighborhood, Address, Postal Code or MLS #" />

</form>

Controller action:
[HttpPost]
public IActionResult HomeBuyersSearchSubmit(SearchFilter filter)
{
     return RedirectToAction("Index", filter);
}

A: I found a work around, but I'd still be curious in knowing what is going on.
For those interested, what I did was changed the "input-group-addon" to a button, and made some slight modifications to the padding and margins to make the button appear like the div counterpart. This also required Bootstrap's "form-inline" on the form. Data binding works as expected now.
<form asp-controller="Search" asp-action="HomeBuyersSearchSubmit" id="Home_Buyers_Search_Form" class="form-inline">

                    <input asp-for="Query" class="form-control" placeholder="City, Neighborhood, Address, Postal Code or MLS #" />
                    <button type="submit" class="input-group-addon"></button>

</form>


text:
Q: error blob uploading Warning: fopen(C:\xampp\tmp\php4FC4.tmp): failed to open stream: No such file or directory i'm trying to create multiple uploading with BLOB.
The above code gives me the following error

Warning: fopen(C:\xampp\tmp\php4FC4.tmp): failed to open stream: No such file or directory

PHP script
$jumlah_file = count($_FILES['userfile']['name']);
$path = pathinfo($_SERVER['PHP_SELF']);

for ($i = 0; $i < $jumlah_file; $i++)
{
    $tmp_file = $_FILES['userfile']['tmp_name'][$i];
    $filetype = $_FILES['userfile']['type'][$i];
    $filesize = $_FILES['userfile']['size'][$i];
    $filename = $_FILES['userfile']['name'][$i];
    $destination = $path['dirname'].
    '/data/'.$filename;
    move_uploaded_file($tmp_file, $_SERVER['DOCUMENT_ROOT'].$destination);
}

$fp = fopen($tmp_file, 'r'); // ERROR LINE
$content = fread($fp, filesize($tmp_file));
$content = addslashes($content);
fclose($fp);

if (!get_magic_quotes_gpc())
{
    $fileName = addslashes($filename);
}

$query = mysql_query("INSERT INTO `konveksi`.`foto` (`id_foto`, `id_daftar`, `id_pesanan`, `foto`) VALUES (NULL, '15', '1','$content');");
mysql_query($query) or die('Error, query failed');

what must I do? Please excuse me if this is stupid question, I am very new to PHP.

A: You already moved the file using  move_uploaded_file($tmp_file, $_SERVER['DOCUMENT_ROOT'].$destination); before the $fp = fopen($tmp_file, 'r');. Afterwards the file is located elsewhere.
The correct code is :
$jumlah_file = count($_FILES['userfile']['name']);
$path = pathinfo($_SERVER['PHP_SELF']);

for ($i = 0; $i < $jumlah_file; $i++)
{
    $tmp_file = $_FILES['userfile']['tmp_name'][$i];
    $filetype = $_FILES['userfile']['type'][$i];
    $filesize = $_FILES['userfile']['size'][$i];
    $filename = $_FILES['userfile']['name'][$i];
    $destination = $path['dirname'].
    '/data/'.$filename;
    $fp = fopen($tmp_file, 'r');
    $content = fread($fp, filesize($tmp_file));
    $content = addslashes($content);
    fclose($fp);
    move_uploaded_file($tmp_file, $_SERVER['DOCUMENT_ROOT'].$destination);
}

if (!get_magic_quotes_gpc())
{
    $fileName = addslashes($filename);
}

$query = mysql_query("INSERT INTO `konveksi`.`foto` (`id_foto`, `id_daftar`, `id_pesanan`, `foto`) VALUES (NULL, '15', '1','$content');");
mysql_query($query) or die('Error, query failed');


text:
Q: Accessing Groovy properties or methods I have a simple question. If I have an HttpResponseDecorator(groovyx.net.http.HttpResponseDecorator) how come I can do response.status to get the response code? When I'm debugging I don't see this property available in the object. I looked up the API and I don't see the status property available. How is response.status working? Am I missing a language feature?

A: The Groovy property is a combination of a private field and getters/setters.
Groovy will then generate the getters/setters appropriately.
For example:
class Person {
    String name
    int age
}

Properties are accessed by name and will call the getter or setter transparently.
I would recommend read more in the Groovy documentation for field and properties.


text:
Q: how to find the coding execution time in c#? I am working in C#, winform and Mysql. (Visual Studio 2010).
In my project all menustrip items are invisable. At the login time its visible which menustrip item user rights. For that i invisible all menu strip,. And I code for visible the menustrip items.
But its take too much time. more then 5 minutes. So I have Few Questions.

*

*How I find this coding execution time?. (My Code Below)....

*Is any special tool is there?.

*How to Reduce the time with effective code?

  private void menuActive(ToolStripItemCollection items)
        {
            hp.getConnStr();
            MySqlConnection connection = new MySqlConnection(hp.myConnStr);
            MySqlCommand command = connection.CreateCommand();
            MySqlDataReader Reader;
            command.CommandText = "select menu_key from mcs_menu_rights where userid ='"+userId+"'";
            connection.Open();
            Reader = command.ExecuteReader();
            while (Reader.Read())
            {
                foreach (ToolStripMenuItem item in items)
                {
                    if (item.Name == Reader[0].ToString())
                    {
                        item.Visible = true;
                    }
                    else
                    {
                        menuActive(item.DropDown.Items);
                    }
                }
            }
            connection.Close();
        }

A: You could profile, but there are some definite improvements I can see straight off:
Seperate out your recusive function away from the database query. This way you query the database once. Note that it's not doing exactly the same, but I'm not sure what that table looks like so you'll have to test it.
private void menuActive(ToolStripItemCollection items)
    {
        hp.getConnStr();
        MySqlConnection connection = new MySqlConnection(hp.myConnStr);
        MySqlCommand command = connection.CreateCommand();
        MySqlDataReader Reader;
        command.CommandText = "select menu_key from mcs_menu_rights where userid ='"+userId+"'";
        connection.Open();
        Reader = command.ExecuteReader();
        while (Reader.Read())
        {
            var nameFromDB = Reader[0].ToString();
            setMenuActiveByName(items, nameFromDB);
        }
        connection.Close();
    }

    //This is the recursive bit, but doesn't re-enquire the database
    private void setMenuActiveByName(ToolStripItemCollection items, string name)
    {
            foreach (ToolStripMenuItem item in items)
            {
                if (item.Name == name)
                {
                    item.Visible = true;
                }
                else
                {
                    setMenuActiveByName(item.DropDown.Items, name);
                }
            }
    }

A: Yes, creating a dbase connection for every single menu item is going to take a while.  You'll need to avoid calling MenuActive() inside the foreach loop.  Make it smarter with a little helper method:
    private static bool EnableMenuItem(ToolStripItemCollection items, string name) {
        foreach (ToolStripMenuItem item in items) {
            if (item.Name == name) {
                item.Visible = true;
                return true;
            }
            else if (item.DropDown.Items.Count > 0 {
                if (EnableMenuItem(item.DropDown.Items, name)) return true;
            }
        }
        return false;
    }

And call it like this:
        ...
        while (Reader.Read())
        {
            EnableMenuItem(items, Reader[0].ToString();
        }

A: Question 1 and 2
var time = TimeAction(() =>
    {
        //CODE here
    });

private static TimeSpan TimeAction(Action action)
{
    var sw = new Stopwatch();
    sw.Start();
    action.Invoke();
    sw.Stop();
    return sw.Elapsed;
}

Question 3
//One loop through all records in database
while (Reader.Read())
{
    //Another loop through all the control
    foreach (ToolStripMenuItem item in items)
    {
        if (item.Name == Reader[0].ToString())
        {
            item.Visible = true;
        }
        else
        {
            menuActive(item.DropDown.Items);
        }
    }
}

Given you have 1000 records in a database and 10 items, this take 10 000 iterations, each including trip to database to serve new data.

A: Use the StopWatch class to time the execution, http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx. Log the time after each step to determine what is taking so long.

A: You can use the StopWatch class for testing performance
StopWatch sWatch = new StopWatch();
sWatch.Start();
// Code comes here
...
sWatch.Stop();
// sWatch.Elapsed // Contains the time interval

It seems like you have a bad recursion there - you run the function on the same collection over and over.

A: Depending on your version of VS, you might be able to use the builtin profiling tools to find where the time is spent.

A: For questions 1 and 2, you can use stopwatch:
Stopwatch watch = new Stopwatch();

watch.Start();
//YOUR CODE HERE
watch.Stop();

Console.WriteLine("Elapsed: {0}",watch.Elapsed);


text:
Q: Make css inline from specific stylesheet not from every part of the code I need a way to get certain CSS attributes for all HTML elements in a page and make them inline. I have a  with custom CSS attributes, for example:

And then:

This is my title

So, I need a script that will make the following change (and only the following):

This is my title

Any thoughts?

A: I'm not quite sure what you mean by "get certain CSS attributes for all HTML elements in a page and make them inline." What are you trying to do?
For individual inline styling, use the span tag:
My mummy has blue eyes.

To style certain elements, as the user above has done with jQuery, use a class tag for each element that you wish to style:
CSS:
    .specialStyle {color: #00d;}
HTML:

...

click here

A: If you only want to do it for h2 elements and for CSS color attribute then the following should work
$('h2').each(function(){
   $(this).css('color', $(this).css('color'));
});

If you want other elements/attributes then you will need to build it out.

A: Basics of CSS:
This will make all h2 tags have a text color of red

I'm red

I'm also red

I'm not red

This will make all tags with the class of chicken be red.

I'm red

I'm also red

I'm not red

If you only want to give one tag a specific property you give it an id

I'm red

I don't really understand what you're looking form, but the property for making something inline is:
display:inline

http://www.w3schools.com/cssref/pr_class_display.asp
If you replace the color:red with display:inline then their properties will change from being red to inline.


text:
Q: Difficulty repopulating viewmodels on post I have various viewmodels that have properties that must be populated. For example, imagine a database table full of countries. I have a create user page, and one of the properties on the viewmodel is List<string> Countries.
Originally I populated this in a parameterless constructor, ie.
public CreateUserViewModel()
{
   this.Countries = new CountryManager().GetCountries();
}

But I read this is a bad practice, and I should pass them in.
public CreateUserViewModel(IEnumerable<string> countries)
{
   this.Countries = countries;
}

But in my post, this data is lost, and if validation fails it redirects to the view, but then the countries property is null.
I am wondering how I should be repopulating this value. Manually putting some code into the controller post method seems bad, eg.
[HttpPost]
public ActionResult CreateUser(CreateUserViewModel vm)
{
  if (Model.IsValid)
  {
      new UserManager().CreateUser(vm);
  }
  else
  {
     vm.Countries = new CountryManager().GetCountries();
     return View(vm);
  }
}

I am struggling to google what is probably a very common question. Any ideas?

A: The rationale behind avoiding parameterless constructors is for inversion of control. The logic in this case would be that Countries is a dependency and by externalizing that dependency (so that it is inject into the class, instead), you make your class less brittle and more open to extension.
However, I would argue that doesn't apply actually in your scenario, because Countries is not really a dependency of your class, but rather of your view. The view model is there to serve the view and is somewhat closed and unextensible anyways as a result. In other words, do follow inversion of control for things like services, repositories, utility classes, etc., but for view models, it's not really necessary or important.
Anyways, here's how I handle this type of thing:
public class FooViewModel
{
    ...

    // Countries is not initialize by a constructor
    public IEnumerable<SelectListItem> Countries { get; set; }
}

Then in your controller:
public class FooController : Controller
{
    internal void PopulateCountryChoices(FooViewModel model)
    {
        // fetch countries
        model.Countries = countries.Select(m => new SelectListItem
        {
            Text = m.Name,
            Value = m.Id.ToString()
        });
    }

    public ActionResult Bar()
    {
        var model = new FooViewModel();
        PopulateCountryChoices(model);
        return View(model);
    }

    [HttpPost]
    public ActionResult Bar(FooViewModel model)
    {
        if (ModelState.IsValid)
        {
            // save and redirect
        }

        PopulateCountryChoices(model);
        return View(model);
    }
}

A: Instead of populating this static data in model, We can populate Dropdownlist values in the view itself -
@Html.DropDownListFor(model => model.State,
                      new SelectList(Utils.GetCountries()),
                      "value",
                      "text",
                      2)

Where Utils is a Helper class which returns all the countries.
This way of populating all the static data (I mean all options of Dropdownlist or Listbox etc) will be taken over by the View, which makes model to be free from holding this data.


text:
Q: How to retrieve particular row data from mysql through android Volley or JSON? Hi guys i have already made login and register using volley library and data gets saved successfully as shown in the snap 1 below. Now my question is how to retrieve particular or specific row data for the particular user when he/she logins?? For example if user admin gets logged in how to fetch her entire row alone
saved data in server side

A: <?php
    $conn = mysql_connect("localhost", "root", "");
    if(isset($conn))
    {
        mysql_select_db('your_db', $conn);
    }
    else
    {
       echo 'Sorry,can not connect to database' ;
    }

   $userid = isset($_GET['id']) ? mysql_real_escape_string($_GET['id']) :  "";
   $qur = mysql_query("select usename,other_fields from `your_tbl` where userid= $userid");
 $result =array();
    while($r = mysql_fetch_array($qur)){
extract($r);
       $result[] = array("usename" => $usename,"other_fields" => $other_fields);
}
$json =array("data"=>$result);
mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);

A: You will have to use server side scripting. Webservice that will fetch that particular row of data.
The script should take your input parameters and give you the out put in Json Array or Object.
You then hit this script using volley and the response you receive can then be utilized for the next step.

A: //call volley get method and get data in success method
public void onSuccess(string response)
{
                try {
                        String s = new String(response);
                        JSONObject jsonObject = new JSONObject(s);

                       if (jsonObject.has("data")) {
                           JSONArray country =jsonObject.getJSONArray("data");
                           for (int i = 0; i < country.length(); i++) {
                            JSONObject cnt = country.getJSONObject(i);
                            String res=cnt.getString("username"));
                           //now you can use res as per your requirement
                        }
                    } catch (JSONException e) {
                   e.printStackTrace();
                } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }


text:
Q: Can't read a file openFileInput Android Trying to open a file
the file exists (and the check returns true)
 but in.available returns 0
if I look at the file with the device monitor I can see the file and it has a size...
if(fileExists(filePath) == false)
                return "ERROR";
            FileInputStream in = openFileInput(filePath);
            if(in.available() <= 0)
            {
                //THIS ALWAYS HAPPENS!!!
            }
            InputStreamReader inputStreamReader = new InputStreamReader(in);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            inputStreamReader.close();

permissions set
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.READ_LOGS" />

A: What does openFileInput do?
It should be doing this:
FileInputStream in = new FileInputStream(new File(filePath));


text:
Q: Defined a window as a class, but unable to call mainloop function I am so trash at coding that I have no idea how to utilise classes to make cool stuff :( --- I'm really new to GUI development, and I'm trying to make a simple maze game with a level selector. I have the maze program squared away, but I am somehow hopeless at Tkinter apparently, since I've been trying constantly for the last hour to find a solution online. As you might have noticed, this is my first post here.
I'm running this in PyCharm, using my decent computer on Windows 10. I'm especially trash at this IDE since I, for some reason, cannot install any libraries/ use any libraries that I see clearly installed in my list of libraries... but that's for another post. As I've mentioned, I've been trying to figure out a simple program for the past hour, but nothing seems to be working.
Nothing I find online is particularly useful, either, and the ones that might be are so hopelessly complex that I cannot understand what they are trying to achieve. I'm looking for a simple solution to a simple problem, and hopefully, this great community can help me out.
import tkinter as tk

class Window():
    def __init__(self):
        self = tk.Tk()
        self.geometry("%dx%d+0+0" % (1920,1080))

root = Window()

root.mainloop()

Expected: Window appears
Observed: Program abruptly ends
Error:
Traceback (most recent call last):
  File "C:/Users/(GD) ShadowPlague/PycharmProjects/GameDesign/Main.py", line 12, in <module>
    root.mainloop()
AttributeError: 'Window' object has no attribute 'mainloop'

A: You create class in wrong way. You can't assign Tk() to self to create correctly class. External root will have nothing to do with internal self. First you create instance Window() and assign to variable root but later you create instance Tk() and assign to self but it will not change instance assigned to root.

First method: create Tk() inside class as self.root and then you use win.root
import tkinter as tk

class Window():

    def __init__(self):
        self.root = tk.Tk()
        self.root.geometry("%dx%d+0+0" % (1920,1080))

win = Window()

win.root.mainloop()

Second method: inherit from Tk(). It needs Window(tk.Tk) and super().__init__
import tkinter as tk

class Window(tk.Tk):

    def __init__(self):
        super().__init__()
        self.geometry("%dx%d+0+0" % (1920,1080))

root = Window()

root.mainloop()


text:
Q: Firebase Admin SDK Upload File to Google Cloud Storage This has been a source of frustration for the past couple of days because the documentation makes it sound like it should be straightforward.
I have a simple HTTP server running locally (Heroku eventually) that I want to use as a passthrough to upload a file to Firebase Cloud Storage. I have a credentials file and am able to successfully init the Firebase App and validate JWTs, but when I try to put an object, I always get an error.
Here is the code --
func main() {
   config := &firebase.Config{
      ProjectID:     "myproject-id",
      StorageBucket: "myproject-id.appspot.com",
   }
   credentialsJSON := os.Getenv("GOOGLE_CREDENTIALS")
   creds := google.Credentials{JSON: []byte(credentialsJSON)}
   opt := option.WithCredentials(&creds)

   app, err := firebase.NewApp(context.Background(), config,
    opt)

   if err != nil {
     log.Fatalln(err)
   }
   ctx, cancel := context.WithTimeout(context.Background(), time.Second*50)
   defer cancel()

   client, err := app.Storage(ctx)
   if err != nil {
     log.Fatalln(err)
   }
   fmt.Println(client)

   bucket, err := client.DefaultBucket()

   object := bucket.Object("foo.png")
   wc := object.NewWriter(ctx)

   r, err := os.Open("/Users/foo/test.png")
   defer r.Close()

   if _, err = io.Copy(wc, r); err != nil {
      log.Error(err)
   }

   if err := wc.Close(); err != nil {
     fmt.Println(err)
     log.Error(err)
   }
}

But this is what I get when I run this code --
 Post "https://storage.googleapis.com/upload/storage/v1/b/myproject-id.appspot.com/o?alt=json&name=foo.png&prettyPrint=false&projection=full&uploadType=multipart": oauth2: Transport's Source is nil

The Firebase Admin SDK documentation clearly states that the service account has full scope control on the storage account, but it seems like there is some mistake on bootstrapping the credentials correctly since the Transport token source is nil.

A: If you're going to directly initialize the google.Credentials struct, then you must specify its TokenSource field. Specifying JSON alone is not sufficient. See how the google.golang.org/api/transport package is implemented:
https://github.com/googleapis/google-api-go-client/blob/144dbf001968463675e3221ab95bce7a93039a28/transport/http/dial.go#L81-L98
Notice how it only cares about creds.TokenSource.
The more common way to pass credentials to the Admin SDK is via option.WithCredentialsJSON(p []byte).


text:
Q: How to write/modify/add some text in a file stored in azure file storage? My goal is to modify a .txt file in azure file storage using WindowsAzure.Storage API. I would like to know if there is any method to add some text in the file.
Is it easier to use the System.IO API?
I've already tried the cloudFileStream.Write() but it didn't work.
Thank you

A: The sample on https://github.com/Azure/azure-storage-net/blob/master/Test/WindowsRuntime/File/FileStreamTests.cs shows you how to do this.
 public async Task FileOpenWriteTestAsync()
        {
            byte[] buffer = GetRandomBuffer(2 * 1024);
            CloudFileShare share = GetRandomShareReference();
            try
            {
                await share.CreateAsync();

                CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1");
                using (CloudFileStream fileStream = await file.OpenWriteAsync(2048))
                {
                    Stream fileStreamForWrite = fileStream;
                    await fileStreamForWrite.WriteAsync(buffer, 0, 2048);
                    await fileStreamForWrite.FlushAsync();

                    byte[] testBuffer = new byte[2048];
                    MemoryStream dstStream = new MemoryStream(testBuffer);
                    await file.DownloadRangeToStreamAsync(dstStream, null, null);

                    MemoryStream memStream = new MemoryStream(buffer);
                    TestHelper.AssertStreamsAreEqual(memStream, dstStream);
                }
            }
            finally
            {
                share.DeleteIfExistsAsync().Wait();
            }
        }

A: If you want to add some text(append to the existing data) to the file on azure file storage, there is no direct method. You need to download it and then upload with the text you want to append.
            string accountName = "xxx";
            string key = "xxx";
            var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, key), true);
            var share = storageAccount.CreateCloudFileClient().GetShareReference("testfolder");
            CloudFile file1 = share.GetRootDirectoryReference().GetFileReference("a.txt");

            //if you want to append some text from local file
            var stream1 = File.OpenRead("your file path in local, like d:\hello.txt");
            string from_local_file = (new StreamReader(stream1)).ReadToEnd();

            //if you just want to add some text from string, directly use the string
            //string from_local_file ="the text I want to append to azure file";

            //download the content of the azure file
            string from_azure_file = file1.DownloadText();

            //this does the trick like appending text to azure file, not overwrite
            file1.UploadText(from_azure_file + from_local_file);

If you want to directly upload text to file stored on azure file storage, you should use one of the following methods: UploadText() / UploadFromFile() / UploadFromStream().
Note that this will overwrite the existing data in the azure file.
If you want to update the context of azure file, you can use WriteRange() method. But it has some limitations, if you're interesting about it, I can provide you some code.


text:
Q: AngularJS / Strange behavior while validating email uniqueness I have a form controlled by Angular, and I expect this to be aware of potential duplicated user's email.
My concerned code is there: http://plnkr.co/edit/XQeFHJTsgZONbsrxnvcI
It contains both directives:

*

*ngFocus: to be able to have the information whether any inputs is on focus or blur.
          It also takes care about a hasVisited variable in order to avoid to validate      the input on blur if it hasn't been reached at least once by the user.

*emailUnique: executing a simple comparison with the mail already existing (hard-coded), in order to be able to validate or not the email input.

The point is: (don't forget to put "tab" touch to get blur function executed in order to see the field's validation error)

*

*If I enter nothing and go to the Name input (to blur the email input), it displays: The field is required. That's good.

*If I enter a non-valid email like the string "ferfergre", it displays: This email isn't valid.. That's good.

*If then I enter a valid e-mail different from the already existing hardcoded one: (michael@gmail.com), no error is displayed. That's good.

*If I enter the existing mail: michael@gmail.com, it displays: This email already exists.. That's good since it warns about it.

*However, if at least once during the DOM cycle, an e-mail was judged "This email already exists", then even if I change it to a new valid one, this error stays...

Question: How to deal with the last case ?
I have two assumptions:

*

*Order of HTML attributes would matter: autofocus email-unique ng-focus required

*setValidity method in emailUnique directive code avoids ctrl to be $valid again, and then prevents the mail comparison to be executed again.

A: Just remove this snippet from your parser function:
if(!ctrl.$valid){
    return viewValue;
}

This code was preventing the mail comparison to be executed again.
With this snippet there, the code below it (which does the comparison) will only run if the control is valid, but will never run if the control is invalid.
Updated plunker: http://plnkr.co/edit/6q3cANiFI4vpWcVEHRvo?p=preview

Edit (better alternative):
If you don't want to perform the comparison when the email field is not valid for the other rules ("required" and "email"), then you will need to check also for ctrl.$error. Instead of removing the snippet mentioned above, just change it to:
if(!ctrl.$valid && !ctrl.$error.emailUnique){
    return viewValue;
}

This way, it will only return if the control is invalid but due to other rule (not the emailUnique one).
Updated plunker: http://plnkr.co/edit/IDQitVkeHHDyJlcsatMy?p=preview


text:
Q: About the $PG(3,2)$ square representation I'm struggling since a while about understanding Curtis' MOG. To land there, I'm going through Cullinane's seminal square representation of $PG(3,2)$, as depicted here:
http://finitegeometry.org/sc/pg/dt/ortholatin.html
It's not clear to me how those square matrices are gotten. I mean, which coordinates you have to assign to the $15$ $PG(3,2)$ points to got those lines and planes? Are the "natural" binary $15$ first numbers enough to achieve that?
A similar explanation can be grasped from wikipedia, on $PG(3,2)$ square representation explanation:

A $3-(16,4,1)$ block design has $140$ blocks of size $4$ on $16$ points, such that each triplet of points is covered exactly once. Pick any single point, take only the $35$ blocks containing that point, and delete that point. The $35$ blocks of size $3$ that remain comprise a $PG(3,2)$ on the $15$ remaining points. If these $16$ points are arranged in a $4 \times 4$ grid and assigned $4-\text{bit}$ binary coordinates like in a Karnaugh map for example, one gets the square representation. Geometrically, the $35$ lines are represented as a bijection with the $35$ ways to partition a $4 \times 4$ grid into $4$ regions of $4$ cells each, if the grid represents an affine space and the regions are $4$ parallel planes.

Any help on how this construction has been achieved, is highly appreciated. Thanks


text:
Q: only show Typoscript breadcrumb when more then 1 I try to create a breadcrumb that is only shown subpages. So far I have this code:
lib.breadcrumb = HMENU
lib.breadcrumb {
   special = rootline
   special.range = 1|-1
   wrap =  |
   1 = TMENU
   1 {
   noBlur = 1
      NO {
           allWrap =   |
            stdWrap.htmlSpecialChars = 1
         }
      CUR = 1
      CUR {
        doNotLinkIt = 0
        allWrap =   |
        }
      }
}

(range is 1 cause 0 is something special).
So on page1 I don't want to show the breadcrumbs. On page1.1 that is a subpage from page1 I want to see th breadcrumb like page1 > page1.1.
My Problem is, I don't find a way to only show the breadcrumbs on subpages. Any idea?

A: On option would be to use a condition of type treeLevel.
Just wrap your code in:
[treeLevel = 2,3,4,5,6,7]
    # ... Your code here
[global]

Or clear the menu on levels 0 and 1:
[treeLevel = 0,1]
    lib.breadcrumb >
[global]


text:
Q: Multiple elements with different parents share the same width I have bunch of inputs with labels declared like this:
<Form inline>
    <FormGroup>
        <ControlLabel>Label</ControlLabel>
        <FormControl />
    </FormGroup>
    <FormGroup>
        <ControlLabel>Another Label</ControlLabel>
        <FormControl />
    </FormGroup>
    <FormGroup>
        <ControlLabel>Some very long label</ControlLabel>
        <FormControl />
    </FormGroup>
</Form>

I would like to align them like this:

All labels to share the same width, but the width should be width of the widest element, which is unknown at design time.
Is it possible to do it in CSS in latest browsers? If no, any react component to help?