text:
Q: tcpdump prints nothing while trying to listen communication with sip server The following command
sudo tcpdump -nqt -s 0 -A -i eth0 port 5060

works and prints incoming SIP messages.
Now I want to see entire communication and entering the IP address of the SIP server:
sudo tcpdump -nqt -s 0 -A -i eth0 host 208.73.146.95

and it prints nothing.
Why?

A: I think your interface might not be in promiscuous mode. Without this, you can only sniff traffic that comes from your interface or is addressed to it. For enabling promiscuous mode run this command:
sudo ifconfig eth0 promisc

I hope this will solve your problem.


text:
Q: ASP.Net/MVC - For roles there is Role Management - Is there any parallel for Feature Management? Is there anything already built as a library/nuget package etc. that provides for feature management in any ASP.Net/MVC application? What I am referring to as a feature is something like modules : data entry module, simple reports module, advanced report module, forecasting.
If a user purchases a basic license, he/she gets access to only - data entry module & simple reports module.
If a user purchases a professional license, he/she gets access to - data entry module & simple reports modul & advanced report module.
If a user purchases an enterprise license, he/she gets access to all - data entry module, simple reports module, advanced report module, forecasting.
My concept that I am referring to is something that is similar to the role management concept, but not exactly the same - How a user has access a certain role and roles have access to pages/action methods.
While developing quite a few applications I have run into this scenario - User should be allowed access to a section not only because they have a particular role, but also they have purchased a certain feature in the app. NOTE: This does not boil down so simply assigning a corresponding role to the user, since a good many roles would have access to a particular feature in the application.
Also, I see a feature as time bound - having a start date and an end date (the end date is based on the period for which the user has paid for a feature), unlike role implementation in the ASP.Net Membership provider OR the simplemembership provider where there is no concept of dates with the roles.

Update: What I am trying to say is that "Features" determine the number of modules you have access to in the application and the "Role" determines how much of within the module you have access to.
Is building a custom solution an alternative or is there anything readymade (free or paid) that is available out there? Just don't want to reinvent the wheel!
Thanks in advance for looking at my question.

Thanks for the responses thus for.
My thought was more on the lines of building something so much into the framework such that you can draw a one-to-one with how Roles work:
User.IsInRole("Admin") ==> Account.HasModule("Banking")
Similar to how the Authorization information in configured in web.config, I should be able to write:
<allow modules="Banking,Finanace"/>

A: I don't think any such feature is inbuilt in asp.net security/membership, but that is very easy to develop and you will not have to purchase. as this is more about how much your features/modules are independent (loosely coupled).
I think this architecture will give you basic solution:
create a table to store all modules list for which you have given licence to the client,
and on load of every module just verify that he has the proper module key stored in that table. if yes then he is allowed to use that module (then it will check for role & membership)..

redpajama_set_name: RedPajamaStackExchange


text:
Q: ClassCastException Adventure I have -
class A {
    // contains certain set() and get() methods
}

class B extends A {
    public A getAotherMethod() {
      A a = new A();
      // Contains some logic
      return a
      }
}

class C extends B {
    // contains certain set() and get() methods
}

class D {
    public Object getMethod() {

      B b = new B();
      // Contains some logic
      return b.getAnotherMethod()
     }
}

public static void main(String[] args) {
    A a = new A();
    B b = new B();
    C c = new C();
    D d = new D();
    c = (C) d.getMethod(); // This is giving me ClassCastException
}

A: d.getMethod();

This will call b.getAnotherMethod() internally, which has
A a = new A();
// Contains some logic
return a

The object of class A cannot cast to class C
We can assign subclass object to  superclass reference but we cannot assign superclass object to subclass reference what is done by you in this case.


text:
Q: Cannot create Struct with CGRect based on super.view.frame I'm trying to create a lookup of CGRect objects but I'm hitting a roadblock.
If I were to initialise a CGRect in viewDidLoad() it would look something like:
let myRect = CGRect(x: (view.frame.width / 2) - 50, y: (view.frame.height / 2) - 50, width: 100, height: 100)

but if that is within a Struct it flags:
'mainViewController.Type' does not have a member named 'view'

It would seem that I'm going about this the wrong way, so could someone shed some light on a better way to implement what I'm after?
Thanks very much.


text:
Q: Stop Activity on Timeout I am starting an ActivityB from ActivityA using startActivity(intent), and then I start a CountDownTimer.
Now on timeout, I want to end ActivityB and have the ActivityA on foreground again.
Is it possible to stop an Activity from another?

A: On Activity B do this -
 // 30 seconds coundowntimer
 new CountDownTimer(30000, 1000) {

     public void onTick(long millisUntilFinished) {

     }

     public void onFinish() {
       finish() // finish ActivityB
     }
  }.start();

Don't call finish on ActivityA when you start ActivityB or make it singleInstance otherwise instead of finish() call startActivity(ActivityB.this,ActivityA.class) in onFinish().

A: Some code would help out tremendously to understand what you are doing. However, you could easily put the CoundtDownTimer in ActivityB and start it in its onCreate(). Then when it finishes just call finish() in ActivityB and as long as you haven't called finish() on ActivityA then you should get your desired result.
If this is not what you want then please supply some code and explain your issue a little better.


text:
Q: Core-UI React CMultiSelect reset not working I am trying to reset Core UI ReactJS CMultiSelect component with Reset button. I have used setState method to reset the value. As soon as I click on the reset button, the state value changes, but immediately onChange method of CMultiSelect is called and the existing value is retained.
Below is the code snippet I'm trying.
import React from 'react'
import { CRow, CMultiSelect, CFormInput, CButton } from '@coreui/react-pro'
class TestForm extends React.Component<{}, { textVal: string; dropdownVal: string[] }> {
  constructor(props: any) {
    super(props)
    this.state = { textVal: '123', dropdownVal: [] }
  }
  setTextVal(newVal: string) {
    this.setState({ textVal: newVal })
  }
  setTest(newVal: string[]) {
    this.setState({ dropdownVal: newVal })
  }
  render() {
    return (

          <CFormInput
            type="text"
            value={this.state.textVal}
            onChange={(evt) => {
              this.setTextVal(evt.target.value)
            }}
          ></CFormInput>

          <CMultiSelect
            multiple={false}
            options={[
              {
                value: '1',
                text: '1',
                selected: this.state.dropdownVal.indexOf('1') >= 0,
              },
              {
                value: '2',
                text: '2',
                selected: this.state.dropdownVal.indexOf('2') >= 0,
              },
              {
                value: '3',
                text: '3',
                selected: this.state.dropdownVal.indexOf('3') >= 0,
              },
            ]}
            onChange={(val) => {
              console.log('on change called', val)
              this.setTest(
                val.map((x) => {
                  return x.value.toString()
                }),
              )
            }}
          ></CMultiSelect>

          <CButton
            className="mt-3"
            type="reset"
            value="Reset"
            onClick={() => {
              this.setTest([])
              this.setTextVal('')
            }}
          >
            Reset
          </CButton>

    )
  }
}
export default TestForm

When I hit the reset button, value of the text field resets, but not the multi-select dropdown.

A: try calling the reset method on the component instance. You can do this by saving a reference to the CMultiSelect instance in your component's state, and then calling the reset method on that instance in your reset handler.
class MyComponent extends React.Component {
  state = {
    select: null,
  };

  handleReset = () => {
    this.state.select.reset();
  }

  render() {
    return (

        <CMultiSelect
          ref={(select) => this.setState({ select })}
          onChange={this.handleChange}
        />
        <button onClick={this.handleReset}>Reset</button>

    );
  }
}


text:
Q: Difference in results between C# and C++ implementation (generate unique permutations) I feel super silly , but I can't figure this out.
I am trying to solve one of the questions from Leetcode - https://leetcode.com/problems/permutations-ii/. I came across one solution in C++ that didn't know how it works, so I decided to try it with debugger.
I implemented it in C#, but I get different result. I can't figure out why, to me the code is the same.
Here is the C++ code:
#include <iostream>     // std::cout
#include <algorithm>    // std::sort
#include <vector>

using namespace std;

void sw(vector<int> &num, int i, int j) {
    int tmp = num[i];
    num[i] = num[j];
    num[j] = tmp;
}

void recursion(vector<int> num, int i, int j, vector<vector<int> > &res)
{
    if (i == j - 1) {
        res.push_back(num);
        return;
    }
    for (int k = i; k < j; k++) {
        if (i != k && num[i] == num[k]) continue;
        sw(num, i, k);
        recursion(num, i + 1, j, res);
    }
}

vector<vector<int> > permuteUnique(vector<int> &num) {
    sort(num.begin(), num.end());
    vector<vector<int> >res;
    recursion(num, 0, num.size(), res);
    return res;
}

int main()
{
    int myints[] = { 1, 1, 2 };
    std::vector<int> fifth(myints, myints + sizeof(myints) / sizeof(int));
    auto r = permuteUnique(fifth);
    cout << "Count: " << r.size() << "; " ;

    return 0;
}

Result of the run is: [1, 1, 2], [1, 2, 1], [2, 1, 1]
Here is the C# Code:
public class T47_Permutations_Unique
    {
        public static IList<IList<int>> PermuteUnique(int[] nums)
        {
            if (nums == null || nums.Length == 0)
            {
                return null;
            }

            IList<IList<int>> result = new List<IList<int>>();
            Array.Sort(nums);
            ComputeInternal(nums, result, 0, nums.Length);

            return result;
        }

        private static void ComputeInternal(int[] num, IList<IList<int>> result, int i, int j)
        {
            if (i == j-1)
            {
                var row = new List<int>();
                for (int z = 0; z < num.Length; z++)
                {
                    row.Add(num[z]);
                }
                result.Add(row);
                return;
            }
            for (int k = i; k < j; k++)
            {
                if (i != k && num[i] == num[k])
                {
                    continue;
                }
                Swap(num, i, k);
                ComputeInternal(num, result, i + 1, j);
            }
        }

        private static void Swap(int[] input, int i, int j)
        {
            var tmp = input[i];
            input[i] = input[j];
            input[j] = tmp;
        }
    }

[Fact]
        public void SmokeTest()
        {
            var input = new int[] {1, 1, 2};
            var result = T47_Permutations_Unique.PermuteUnique(input);
            Assert.Equal(3, result.Count);
        }

And the result is (5 elements instead of 3): [1, 1, 2], [1, 2, 1], [2, 1, 1], [1, 1, 2], [1, 2, 1]
Both apps are essentially the same, why is there a difference in results?


text:
Q: mongose.connect(. . .) is not a function I am trying to connect to a MongoDB database using the mongoose NPM module. But whenever I try the connect function, I get mongoose.connect(...) is not a function
I don't believe this has to do anything with my code, so, I'm guessing it's a problem related to the module. Not sure though.
Any help would be appreciated!

A: Right, so.
Just to clarify, I had the wrong MongoDB URI when trying to connect. So, that's what caused the issue. No help is needed, thanks.


text:
Q: looking for a numerical solution to the equation I was solving multiple equations and came down to the simplified version below:
import sympy as sp
Diff = sp.Symbol('Diff')
eq1 = 0.0363984561703043*Diff**(-0.333333333333333)*(0.01 - 1.288e-18*(2.576e-18*Diff - 2.79999921278e-7)**(-0.5)) + 0.0363984561703043*Diff**(-0.333333333333333)*(17857.1428571429*(2.576e-18*Diff - 2.79999921278e-7)**0.5 - 434782608695.652) + 1299.94486322516*Diff**0.666666666666667
ans = sp.solve(eq1 - 1, Diff)
print(ans)

I need help to solve for the symbol (Diff)? I have tried solve() and nsolve() but it didn't give a solution with the message:

'ValueError: Could not find root within given tolerance.
  (0.00104637107257089658395 > 2.16840434497100886801e-19) Try another
  starting point or tweak arguments.'

A: Firstly, let us try plotting your function (I had to increase the x-axis limits several times until I finally found something resembling a root):
eq = sp.Abs(eq1 - 1)
xs = np.linspace(-1e6, 2e7, 100)
ys = [eq.evalf(subs={Diff: x}) for x in xs]
plt.plot(xs, ys)
plt.hlines(0, -1e6, 2e7)

OK, so if there would be a root, it must be located somewhere around 1.0-1.5*10^7. Now observe the imaginary part of your equation in that region:
eq = sp.im(eq1 - 1)
xs = np.linspace(1e7, 1.5e7, 100)
ys = [eq.evalf(subs={Diff: x}) for x in xs]
plt.plot(xs, ys)
plt.hlines(0, 1e7, 1.5e7)

It does not reach zero, which means your function does not have a root, it seems. It does get quite close to zero, though, at that point where we saw the absolute value chart nearly touch it. You can find this point by solving just for the real part:
sp.nsolve(sp.re(eq1 - 1), Diff, 1e7)
> 12173913.2204420

eq1.subs(Diff, 12173913.2204420).evalf()
0.999999925494194 + 0.00149499418051858*I


text:
Q: IBM - Navigator Custom Action I need to develop a IBM ICN plugin that do the following steps.

*

*the user search for an item of class A;

*the user select one item and click on 'Action Menu' and choose my custom action called 'Show other document'

*after that the user views a document of class B.

I developed a SamplePluginAction starting from IBM Sample example, I edited services so in the response I have the documentId of class B but for now I can only open a simple Message Dialog where I can see the documentId.
I think that is not the right way. I see that there is OpenActionDocument but I can't find an example.
Can anyone help me to understand which steps I have to implement? Thanks.

A: I think the simplest solution would be to construct a url for viewing document and open that in a new browser window.
See https://www.ibm.com/docs/en/content-navigator/3.0.x?topic=client-constructing-url-content-navigator#eucco106 => "Viewing documents" as for how to construct an url for viewing a document.


text:
Q: Nuxt update session cookie with each request I am building a Nuxt app that uses fastify for the backend API. I am using httpOnly session-cookies for authentication. So far everything works fine but the issue i have is that Nuxt just has a hardcoded cookie timeout of 30 minutes. I have updated this to 24hrs but what i really want to do is have Nuxt refresh the timeout after each request.
I see in my database that the fastify session cookie get updated after each request and the session expiration gets updated after ANY user API request. So, this looks like the backend is functioning correctly but the frontend need to update the auth._token_expiration.local value.
You can see in the config that i manually set the maxAge to 24hrs, cant i have the frontend update the auth._token_expiration.local value automatically when making successful API requests? my token is stored as sessionId
nuxt.config.js
  auth: {
    redirect: false,
    strategies: {
      local: {
        token: {
          required: false,
          type: false,
          maxAge: 86400 // seconds - 1 day
        },
        user: { property: false },
        endpoints: {
          login: {
            url: '/user/login',
            method: 'post',
            withCredentials: true
          },
          logout: {
            url: '/user/logout',
            method: 'post',
            withCredentials: true
          },
          user: {
            url: '/user/profile',
            method: 'get',
            withCredentials: true
          }
        }
      },
      localStorage: false,
      cookie: true
    }
  },

A: So i discovered that the sessionId Expires data DOES get updated after each api request, so that is good. To make this function i also had to set the nuxt.config token maxAge to 0. This solved my issues.


text:
Q: Looping list of object inside partial view returning null values in post I have a partial view inside which loops my Availability object for getting values from text box. I have added my code in here.
public class Availability
    {
        public int ID { get; set; }
        public string Name{ get; set; }
        public string Address { get; set; }
        public string Gender { get; set; }
        public int Adult { get; set; }
        public int Child { get; set; }
    }

My controller class:
public class HomeController : Controller
    {
        List<Availability> lst = new List<Availability>();

        public ActionResult Index()
        {
            Availability aa = new Availability();
            Availability a1 = new Availability();
            Availability a2 = new Availability();
            Availability a3 = new Availability();
            lst.Add(aa);
            lst.Add(a1);
            lst.Add(a2);
            lst.Add(a3);

            return View(lst);
        }
        public ActionResult ListOfPost(IEnumerable<WebApplication1.Class.Availability> aaa)
        {

            return View();
        }
    }

Here, list count will vary. Can be more that 10.
My main view:
@model List<WebApplication1.Class.Availability>
@{
    ViewBag.Title = "Home Page";
}

    Index page
@Html.Partial("_Availability", Model)

My partial view:
@model IEnumerable<WebApplication1.Class.Availability>

    @Html.ActionLink("Create New", "Create")

@using (Html.BeginForm("ListOfPost", "Home", FormMethod.Post))
{

                @Html.DisplayNameFor(model => model.Name)

                @Html.DisplayNameFor(model => model.Address)

                @Html.DisplayNameFor(model => model.Gender)

                @Html.DisplayNameFor(model => model.Adult)

                @Html.DisplayNameFor(model => model.Child)

        @foreach (var item in Model)
        {

                    @Html.EditorFor(modelItem => item.Name, new { @class = "Name" })

                    @Html.EditorFor(modelItem => item.Address, new { @class = "Address" })

                    @Html.EditorFor(modelItem => item.Gender, new { @class = "Gender" })

                    @Html.EditorFor(modelItem => item.Adult, new { @class = "Adult" })

                    @Html.EditorFor(modelItem => item.Child, new { @class = "Child" })

        }

    <input id="btnSubmit" class="btn btn-default" type="submit" value="Submit">
}

My error is - When I click on submit to post data to ListOfPost() ActionResult, parameter aaa is returning null value. I doubt that the cause of issue is name will be save for all text box.
How can I get user entered values in post???

A: You need a viewmodel class that holds an IEnumerable<Availability> availabilities property and return that in the view.


text:
Q: Workaround for Sass variable interpolation in nested loop? I realize this is a big issue is Sass right now, and have looked at some of the solutions out there but I have a set of maps, and I am trying to create a loop as in:
    //Color chords
$chord1: (color1:orange,  color2: magenta, color3: gray, color4: yellow);
$chord2: (color1:magenta, color2: blue,    color3: gray, color4: orange);

%fillcolor {

}

@for $c from 1 through 8 {
    #chord#{$c} {
        @for $i from 1 through 4 {
            .color#{$i} {
                $c1: map-get($chord#{$c}, color#{$i});
                fill: $c1;
                color: $c1;
            }
        }
    }
}

Sass (3.4.5), of course, is choking on $chord#{$c} ("cannot find variable $chord").
Is there a work-around in this situation?

A: You can't use dynamic variable name in SCSS for now but you could use list as shown below.
//Color chords
$chord: (
  (color1:orange,  color2: magenta, color3: gray, color4: yellow)
  (color1:magenta, color2: blue,    color3: gray, color4: orange)
);

@for $c from 1 through length($chord) {
    $subList: nth($chord, $c);
    #chord#{$c} {
        @for $i from 1 through length( $subList ) {
            .color#{$i} {
                $c1: map-get( $subList, color#{$i});
                fill: $c1;
                color: $c1;
            }
        }

    }
}


text:
Q: Evaluate integral over quadratic form What would be the most kosher way to evaluate an integral like this in Mathematica:
$$\int_\mathbb{R^3} \exp\left((x-b)^tA(x-b)\right)dx \ ?$$
Here $A$ is a real symmetric matrix and $b$ some vector in $\mathbb{R^3}$. Should I write everything out in components and integrate the expression
$$ \int_{\mathbb{R}}\int_{\mathbb{R}}\int_{\mathbb{R}}\exp \left( \sum_{i=1}^n\sum_{j=1}^n (x_i-b_i)^tA_{i,j}(x_j-b_j)) \right) dx_1dx_2dx_3 \ , $$
or is there a more elegant way to do this by staying in the "vector notation" without writing the sums?

A: If you give the integral an explicit matrix, then Integrate can solve it:
A = {{-5,-5,7/2},{0,-10,7/2},{0,0,-3}};

Integrate[Exp[(x-b).A.(x-b)], x ∈ FullRegion[3], Assumptions->b ∈ Vectors[3]]

2 Sqrt[2/805] π^(3/2)


text:
Q: How to update a copy/backup of a folder in Windows 10? I have a large directory, which I occasionally want to backup to my NAS and to an external hard drive. I work a lot in this folder, but the majority of data (all my photos and videos) does not change, so deleting the backups and writing the entire folder again seems inefficient and unnecessary. Is there an easy way to update/one-way synchronize these backups and make sure they're exactly the same, i.e. add new files, delete files not present in the original folder anymore, update files with the same name but different checksum, and leave everything else as is? Can Windows 10 do this already on its own? Small command line utilities are fine, but I'd prefer not to install larger applications for this. If such a tool exists, I'd prefer if it was also available for macOS and Linux.
My apologies if this is a common question, but I could not find any solutions to this specific use case.

A: Windows 10 contains the command-line tool robocopy.exe which is a perfect match for copying data sets to external drives e.g. for making a backup.
Especially the parameter /MIR is useful as it allows to mirror a whole directory tree from the source to the destination. Existing files that have the same modification time and size will not be copied again, new and modified field will be copied/overwritten.
Directories and files that exist only in the destination (may be because they have been deleted in the source directory) will be deleted.
My personal favorite robocopy parameter combination for making a backup is this:
robocopy <source> <destination> /MIR /XJ /NDL /NP /TEE /LOG:logfile.txt


text:
Q: Reference type List with order by I have weird situation, I can't explain, can someone help me to understand it?
As my understanding, List is a reference type, it mean that after we change the list inside function Rating, the list will be changed outside the function. But in real it doesn't change after I sorting. Is there any problem that I misunderstand?
class Program
{
    static void Main(string[] args)
    {
        List<User> data = new List<User>
        {
            new User { TotalScore = 0 },
            new User { TotalScore = 3 },
            new User { TotalScore = 4 }
        };
        Rating(data);
        //List data doesnt order descending by TotalScore
    }

    private static void Rating(List<User> data)
    {
        data = data.OrderByDescending(e => e.TotalScore).ToList();
    }
}

public class User
{
    public int Id { get; set; }
    public decimal TotalScore { get; set; }
}

A: List is a reference type, however you should not confuse this with passing an argument by reference into a function. By default, function arguments in C# are passed by value. You are currently passing the data reference by value into Rating, so the data variable in that function is a copy of the reference in the caller. This allows the function to mutate the same list through the reference, but any assignments will only affect the local variable.
To pass a variable by reference you need to use the ref keyword:
private static void Rating(ref List<User> data)
{
    data = data.OrderByDescending(e => e.TotalScore).ToList();
}

and change the call to:
Rating(ref data);


text:
Q: Floating IDE windows in Qt Designer within Qt Creator Is there a way to re-arrange the IDE windows for the  Qt Designer that is embedded into Qt Creator like it is possible with the standalone Designer for Visual Studio?
Edit: Note that Qt Designer is something like an "app-in-an-app" so it behaves differently to Qt Creators UI.

A: You can't completely undock views (as in create a completely separate window) in Qt Creator (sadly) but you can rearrange things a little bit:

*

*Go to Window -> Views and make sure the Automatically Hide View Title Bars is unchecked. This will allow the different views to become movable (and not just resizeable as per default) and partially undock from the IDE. Not that not all views are movable even. For example the sidebar is a completely different animal here and you are stuck with it as it is.

*Each movable view's title bar contains two buttons (on the right side) - one that enables moving and one that closes the view.

*Click on the first button and then click on the title bar of the view and drag it around. If you drag it within the IDE Qt Creator will rearrange the other views to free some space (it gives you a nice hint) where you can drop it. If you leave it like that (floating) you can have a pseudo-undocked state of that view.

I use pseudo-undocked because (at least on Linux) the view is not actually a separate window and you can't drag it to other workspaces (if you have multiple; not that uncommon in Linux distros). But it's as close as you can get.


text:
Q: React-Native: Apple Mach-O Linker Error, Directory not found for CocoaAsyncSocket Having problems with react native. Getting this error when compiling with xcode:
ld: warning: directory not found for option '-L-L/Users/username/Library/Developer/Xcode/DerivedData/InterfacingConsumerHealthPeripherals-gbyevwticojtxmcicmilnnmtlowd/Build/Products/Debug-iphonesimulator/CocoaAsyncSocket'
ld: library not found for -lCocoaAsyncSocket
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I am unsure whats wrong. I have reset my podfile and node_modules many times. Tried other solutions removing linked binaries and flipper. I have tried npm install and removing library search paths. Nothing seems to work.
My PodFile:
require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/react-native-unimodules/cocoapods.rb'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

platform :ios, '12.0'

target 'InterfacingConsumerHealthPeripherals' do
  use_unimodules!
  config = use_native_modules!

  use_react_native!(:path => config["reactNativePath"])
  #use_frameworks!

  # Enables Flipper.
  #
  # Note that if you have use_frameworks! enabled, Flipper will not work and
  # you should disable these next few lines.
  use_flipper!({ 'Flipper' => '0.74.0' })

  post_install do |installer|
    flipper_post_install(installer)
  end
end

My Dependencies
"dependencies": {
    "@react-native-async-storage/async-storage": "^1.13.4",
    "@react-native-community/art": "^1.2.0",
    "@react-native-community/cli-platform-ios": "^4.13.0",
    "@react-native-community/masked-view": "0.1.10",
    "@react-navigation/bottom-tabs": "^5.11.1",
    "@react-navigation/drawer": "^5.11.2",
    "@react-navigation/native": "^5.8.9",
    "@tensorflow/tfjs": "^3.0.0",
    "@testing-library/react-native": "^7.1.0",
    "@tradle/react-native-http": "^2.0.1",
    "@unimodules/react-native-adapter": "^5.4.0",
    "assert": "^2.0.0",
    "asyncstorage-down": "^4.2.0",
    "base64-arraybuffer": "^0.2.0",
    "expo": "^37.0.12",
    "expo-application": "^2.3.0",
    "expo-auth-session": "^3.1.0",
    "expo-constants": "^10.0.1",
    "expo-linking": "^2.1.1",
    "expo-random": "^9.0.1",
    "expo-secure-store": "^9.2.0",
    "expo-splash-screen": "~0.6.2",
    "expo-status-bar": "~1.0.2",
    "expo-updates": "~0.3.2",
    "jest-expo": "^38.0.2",
    "jest-fetch-mock": "^3.0.3",
    "moment": "^2.29.1",
    "react": "16.13.1",
    "react-devtools": "^4.10.0",
    "react-dom": "16.13.1",
    "react-native": "~0.63.3",
    "react-native-calendar-picker": "^6.1.5",
    "react-native-dialog": "^6.1.2",
    "react-native-elements": "^3.0.0-alpha.1",
    "react-native-gesture-handler": "~1.7.0",
    "react-native-os": "^1.2.6",
    "react-native-randombytes": "^3.6.0",
    "react-native-reanimated": "^1.7.0",
    "react-native-responsive-screen": "^1.4.2",
    "react-native-safe-area-context": "3.1.4",
    "react-native-screens": "~2.10.1",
    "react-native-svg": "9.0.1",
    "react-native-testing-library": "^6.0.0",
    "react-native-udp": "^4.1.2",
    "react-native-unimodules": "^0.9.1",
    "react-native-vector-icons": "^7.1.0",
    "react-native-web": "^0.15.0",
    "react-navigation": "^4.4.3",
    "react-navigation-drawer": "^2.6.0",
    "rn-apple-healthkit": "^0.8.0",
    "stream-browserify": "^3.0.0",
    "timers-browserify": "^2.0.12",
    "tty-browserify": "0.0.1",
    "url": "^0.11.0",
    "util": "^0.12.3",
    "victory-native": "^35.3.1",
    "wav-decoder": "^1.3.0"
  }

Any help is appreciated :). Unsure whats wrong

A: Instead of use_flipper!({ 'Flipper' => '0.74.0' }) in your pod file, use:

use_flipper!({ 'Flipper-Folly' => '2.3.0' })

*

*then delete your Podfile.lock

*inside the ios folder in terminal run pod install

*go back to the project folder and run react-native run-ios or npx react-native run-ios depending on your environment.


text:
Q: jQuery show & hide if not containing text in div above I'm trying to display 'dd' content if the above 'dt' contains the following 'Candidate Name:' else hide 'dd', My snippet below is almost there but it shows all 'dd' not just the ones with the above text 'Candidate Name:' If anyone could help me out I'd greatly appreciate it.
JS CODE:
$('.order_table_item .variation dt').each(function () {
    if ($(this).text() == 'Candidate Name:') {
        $('.order_table_item .variation dt').next().show();
    } else {
        $(this).hide();
    }
});

A: Replace
$('.order_table_item .variation dt').next().show(); with $(this).next().show();
$(this) refers to the current element
using $('.order_table_item .variation dt').next().show(); will show all $('.order_table_item .variation dt').next()
js
$('.order_table_item .variation dt').each(function () {
    if ($(this).text() == 'Candidate Name:') {
        $(this).next().show();
    } else {
        $(this).hide();
    }
});

A: Try
$('.order_table_item .variation dt').each(function () {
    if ($(this).text() == 'Candidate Name:') {
        $(this).next().show();
    } else {
        $(this).hide();
    }
});


text:
Q: Cannot retrieve Value with ID of 133705167 When running a SPARQL UPDATE query (DELETE/INSERT) the message :

Cannot retrieve Value with ID of 133705167

is given in the GraphDB workbench. This happened after a large update query successfully finished.
Any ideas as to why this message occurred?

A: GraphDB database engine represents the RDF data into two parallel collections named entity pool and statement collections. The entity pool is a dictionary-like structure mapping the RDF values to the internal identifiers. The statement collections are the actual indexes storing the subject predicate object context data organised as a paged structure.
The exception Cannot retrieve Value with ID of 133705167 indicates that the statement collections contains a value which cannot be retrieved from the entity pool. Few possible scenarios can lead to such inconsistency:

*

*The database collections were manually edited or copied while the database was running

*You hit an unknown database bug

I recommend you first to scan your image with the storage tool. It will detect and report all data inconsistencies. Later once you determine the full scope of the issue, you can recover your repository content, by dumping it to RDF file with the export. All internal IDs without RDF value will be skipped.


text:
Q: Correcting the text cursor in a UITextField when replacing its text I am implementing shortcut substitution for text typed into a UITextField.
For instance, if the text field already contains "a" and he types another "a" after it, I'd replace it with "ä". In another case, if he types "a", then "b", I'd replace it with "XYZ". And if the text contains two consecutive spaces, I like to replace them with a single space.
So, depending on what the user types, I might replace it with either a longer, a shorter, or a same-length text.
The simple way to do that is to implement the [UITextFieldDelegate textField: shouldChangeCharactersInRange: ... delegate function, assign the replacement text to textField.text, and return NO.
But this also requires adjusting the cursor position accordingly, and that's what I'm struggling with, a little.
I am handling this cursor positioning "by hand" currently. It's a bit ugly, and so I wonder if there is a more elegant solution. After all, all the code for handling the cursor position after replacing text (e.g. when selecting, then pasting) is already implemented in the UITextField code anyway. I just wonder if more of it is exposed for needs such as mine and I haven't found it yet.

A: I really think that you don't need textField:shouldChangeCharactersInRange:replacementString:. There is an easy way to solve your requirements and the solution don't have problems with the cursor.
You should add this line of code in your viewDidLoad (self.textField is your UITextField):
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shortcut:) name:UITextFieldTextDidChangeNotification object:self.textField];

then, you should add the selector, e.g.:
- (void) shortcut: (NSNotification*) notification
{
    UITextField *notificationTextField = [notification object];

    if (notificationTextField == self.textField)
    {
        [self checkDoubleA:notificationTextField];
        [self checkDoubleAB:notificationTextField];
        [self checkDoubleSpace:notificationTextField];
    }
}

Then you only need to add the 3 methods to check your shortcuts:
-(void) checkDoubleA: (UITextField*) textField
{
    NSMutableString *string =  [textField.text mutableCopy];
    NSRange range = [string rangeOfString:@"aa"];
    if (range.location == NSNotFound)
    {
        NSLog(@"string was not found");
    }
    else
    {
        [string replaceCharactersInRange:range withString:@"ä"];
    }
    textField.text = string;
}

-(void) checkDoubleAB: (UITextField*) textField
{
    NSMutableString *string =  [textField.text mutableCopy];
    NSRange range = [string rangeOfString:@"ab"];
    if (range.location == NSNotFound)
    {
        NSLog(@"string was not found");
    }
    else
    {
        [string replaceCharactersInRange:range withString:@"XYZ"];
    }
    textField.text = string;
}

- (void) checkDoubleSpace: (UITextField*) textField
{
    NSMutableString *string =  [textField.text mutableCopy];
    NSRange range = [string rangeOfString:@"  "];
    if (range.location == NSNotFound)
    {
        NSLog(@"String was not found");
    }
    else
    {
        [string replaceCharactersInRange:range withString:@" "];
    }
    textField.text = string;
}

You can download a demo of this code here.


text:
Q: QRegularExpression - How to extract string from between two  tags? I am trying to get the text within multiple tags as following:
Text File:
Internal Auto-Configured Settings File
________________________________________
(( Do not attempt to edit it manually ))
________________________________________
# Saved certifications:
<ca>
Text which I want to extract
</ca>
...
<cert>Another text I want to extract</cert>
...

In my code I open the previous file and read its content & store it into a QString. So far I've done the following without any success:
QRegularExpression regex("<ca>(.*)</ca>", QRegularExpression::MultilineOption);
QRegularExpressionMatch match = regex.match(content);
QString ca = match.captured(1);

qDebug() << ca;
qDebug() << "\n\nDone!!";

<< Also did the same for <cert> but I get an empty string for both.

A: <ca>(.*?)<\/ca>|<cert>(.*?)<\/cert>

You can try this.Do no forget to add flag s or DOTALL.
See demo.
http://regex101.com/r/sU3fA2/30

A: Instead of QRegularExpression::MultilineOption, use QRegularExpression::DotMatchesEverythingOption. The problem is due to the fact that . doesn't match new line character in default mode.
Citing the documentation:

The dot metacharacter (.) in the pattern string is allowed to match any character in the subject string, including newlines (normally, the dot does not match newlines). This option corresponds to the /s modifier in Perl regular expressions.

Make sure that </ca> only appear once in the input.
If that is not the case, modify your expression a bit:
"<ca>(.*?)</ca>"

This makes the quantifier lazy (instead of the default greedy), and causes it to match the closest closing tag </ca>.


text:
Q: Thoughtful way to show Klein-4 group is a subgroup of $S_4$ I am learning Klein-4 group $G:=\{id,(12)(34),(13)(24),(14)(23)\}$.
It is easy to show that every element in $G$ is the inverse of itself, as disjoint permutations commutes.
So, to show $G<S_4$, we only need to show $G$ is closed under composition. The obvious way to show that is to compute each composition. Is there any more thoughtful way to prove the closure under composition?

A: Hint: Alternatively, $K_4 \cong C_2 \times C_2 \cong S_2 \times S_2 \hookrightarrow S_4$.
This gives the subgroup $K=\{id,(12),(34),(12)(34)\}$ of $S_4$, not the one in the question, but it is clear that $K$ is closed under composition.


text:
Q: Convert full color image to three color image for e-ink display I'd like to be able to automagically convert full color images down to three color (black / red / white) for an e-ink display (Waveshare 7.5").  Right now I'm just letting the screen handle it, but as expected complex images get washed out.
Are there any algorithms or filters I could apply to make things a bit more visible?
Right now I'm using Python, but I'm not averse to other languages/environments if necessary.
Good image:

Washed out image:

A: You could make your own palette of 3 acceptable colours like this:
magick xc:red xc:white xc:black +append palette.gif

Then you can apply it to your image like this:
magick input.png +dither -remap palette.gif result.png

If you want to send it straight to the frame buffer and it supports RB888, you can try running something like this:
magick input.png +dither -remap palette.gif -depth 8 RGB:/dev/fb0

A: Just adding a bit to Mark Setchell's answer. For printing you might be better dithering your 3 colors.  So here is your image with and without dithering using Imagemagick 7. If using Imagemagick 6, replace magick with convert.
Input:

Create 3 color palette:
magick xc:red xc:white xc:black +append palette.gif

With dithering(default is Floyd-Steinberg):
magick input.png -remap palette.gif result.png

[![enter image description here][2]][2]
With out dithering
magick input.png -dither none -remap palette.gif result2.png

[![enter image description here][3]][3]
If you want Python, then you could try Python Wand. It is based upon Imagemagick.
ADDITION:
To separate the red and black into two image, each of which are represented by black and the rest as white, you can do the following and save as BMP as you want in your comments. (You can do this with or without dithering from above as you desire)
magick result.png -color-threshold "red-red" -negate red.bmp
magick result.png -color-threshold "black-black" -negate black.bmp

Red:

Black:

A: You appear to be choosing the nearest color for each pixel.  See if a dithering algorithm works better for your purposes.  Generally, dithering algorithms take into account neighboring pixels when determining how to color a given pixel.

EDIT: In the case of PIL (the Python Imaging Library), it doesn't seem trivial to dither to an arbitrary set of three colors, at least as of 2012.

A: Just adding a bit to Mark and Fred's answers. I'm using ImageMagick on Raspberry Pi, which is version < 7 and uses "convert". Some of the commands Fred had suggested didn't work for that version. Here's what I did to resize, remap and dither, and split the image into white-and-black and white-and-red sub-images.
# Create palette with red, white and black colors
convert xc:red xc:white xc:black +append palette.gif

# Resize input file into size suitable for ePaper Display - 264x176
# Converting to BMP.
# Note, if working with JPG, it is a lossy
# format and subsequently remapping and working with it results
# in the color palette getting overwritten - we just convert to BMP
# and work with that instead
convert $1 -resize 264x176^ -gravity center -extent 264x176 resized.bmp

# Remap the resized image into the colors of the palette using
# Floyd Steinberg dithering (default)
# Resulting image will have only 3 colors - red, white and black
convert resized.bmp -remap palette.gif result.bmp

# Replace all the red pixels with white - this
# isolates the white and black pixels - i.e the "black"
# part of image to be rendered on the ePaper Display
convert -fill white -opaque red result.bmp result_black.bmp

# Similarly, Replace all the black pixels with white - this
# isolates the white and red pixels - i.e the "red"
# part of image to be rendered on the ePaper Display
convert -fill white -opaque black result.bmp result_red.bmp

I've also implemented in using Python Wand, a Python layer over ImageMagick
# This function takes as input a filename for an image
# It resizes the image into the dimensions supported by the ePaper Display
# It then remaps the image into a tri-color scheme using a palette (affinity)
# for remapping, and the Floyd Steinberg algorithm for dithering
# It then splits the image into two component parts:
# a white and black image (with the red pixels removed)
# a white and red image (with the black pixels removed)
# It then converts these into PIL Images and returns them
# The PIL Images can be used by the ePaper library to display
def getImagesToDisplay(filename):
    print(filename)
    red_image = None
    black_image = None
    try:
        with WandImage(filename=filename) as img:
            img.resize(264, 176)
            with WandImage() as palette:
                with WandImage(width = 1, height = 1, pseudo ="xc:red") as red:
                    palette.sequence.append(red)
                with WandImage(width = 1, height = 1, pseudo ="xc:black") as black:
                    palette.sequence.append(black)
                with WandImage(width = 1, height = 1, pseudo ="xc:white") as white:
                    palette.sequence.append(white)
                palette.concat()
                img.remap(affinity=palette, method='floyd_steinberg')

                red = img.clone()
                black = img.clone()
                red.opaque_paint(target='black', fill='white')
                # This is not nececessary - making the white and red image
                # white and black instead - left here FYI
                # red.opaque_paint(target='red', fill='black')

                black.opaque_paint(target='red', fill='white')

                red_image = Image.open(io.BytesIO(red.make_blob("bmp")))
                black_image = Image.open(io.BytesIO(black.make_blob("bmp")))
    except Exception as ex:
        print ('traceback.format_exc():\n%s',traceback.format_exc())

    return (red_image, black_image)

Here's my writeup on my project on Hackster (including full source code links) - https://www.hackster.io/sridhar-rajagopal/photostax-digital-epaper-photo-frame-84d4ed
I've attributed both Mark and Fred there - thank you!


text:
Q: Disabled Button is still callable The code below creates a GUI with a Button. When I press the Button the Button gets grayed out and after the "Plus" function finishes the Button changes to normal/enabled.
The Problem is that I can still click on the disabled Button, so the "Plus" function starts immediately(is stackable) after the first one finishes.
Does anybody know why this happen?
from tkinter import *
import time
import RPi.GPIO as GPIO

fenster = Tk()
fenster.geometry("840x480+00+150")
GPIO.setmode(GPIO.BCM)
A1S =16 #GPIO Pin 16

# Moves a Steppermotor
def Plus():
    for i in range(1000):
        GPIO.output(A1S, True)
        time.sleep(0.0018)
        GPIO.output(A1S, False)

def GUIsperren(): #Disable Button
    b1["state"] = "disabled"
def GUIentsperren(): #Enable Button
    b1["state"] = "normal"

def moveaxis():
    GUIsperren()
    Plus()
    GUIentsperren()

b1=Button(fenster, text="PLUS", command=moveaxis)
b1.place(x=190, y=180,height=80, width=80)

fenster.mainloop()

I also tried this but get the same result:
def Plus():
    b1["state"] = "disabled"
    for i in range(200):
        GPIO.output(A1S, True)
        time.sleep(0.0018)
        GPIO.output(A1S, False)
    b1["state"] = "normal"


text:
Q: How can I one-hot encode the data which has multiple same values for different properties? I have data containing candidates who look for a job. The original data I got was a complete mess but I managed to enhance it. Now, I am facing an issue which I am not able to resolve.
One candidate record looks like
https://i.imgur.com/LAPAIbX.png
Since ML algorithms cannot work with categorical data, I want to encode this. My goal is to have a candidate record looking like this:
https://i.imgur.com/zzsiDzy.png
What I need to change is to add a new column for each possible value that exists in Knowledge1, Knowledge2, Knowledge3, Knowledge4, Tag1, and Tag2 of original data, but without repetition. I managed to encode it to get way more attributes than I need, which results in an inaccurate model. The way I tried gives me newly created attributes Jscript_Knowledge1, Jscript_Knowledge2, Jscript_Knowledge3 and so on, for each possible option.
If the explanation is not clear enough please let me know so that I could explain it further.
Thanks and any help is highly appreciated.
Cheers!

A: I have some understanding of your problem based on your explanation. I will try and elaborate how I would approach this problem. If that is not solving your problem, I may need more explanation to understand your problem. Lets get started.

*

*For all the candidate data that you would have, collect a master
skill/knowledge list

*This list becomes your columns

*For each candidate, if he has this skill, the column becomes 1 for his record else it stays 0

*This is the essence of one hot encoding, however, since same skill is scattered across multiple columns you are struggling with autoencoding it.

An alternative approach could be:

*

*For each candidate collect all the knowledge skills as list and assign it into 1 column for knowledge and tags as another list and assign it to another column instead of current 4(Knowledge) + 2 (tags).

*Sort the knowledge(and tag) list alphabetically within this column.

*Auto One hot encoding after this may yield smaller columns than earlier

Hope this helps!


text:
Q: How to prevent users from visiting Deleted action method directly? Scenario:
Clicking a delete hyperlink on one product of a product list will invoke /Product/Delete HttpGet action method. The user then clicks the confirmation button to invoke  /Product/Delete HttpPost action method which in turn redirect the user to /Product/Deleted HttpGet action method.
I want to prevent users from skipping /Product/Delete and  directly invoking /Product/Deleted.

A: Before redirecting put something into TempData. Then in the Deleted action verify if this something is present in the TempData.
[HttpPost]
public ActionResult Delete()
{
    // TODO: Delete
    TempData["deleted"] = true;
    return RedirectToAction("deleted");
}

public ActionResult Deleted()
{
    if(TempData["deleted"] == null)
    {
        throw new HttpException(404, "not found");
    }
    return View();
}

You should be aware that there is a price to pay with this. If the user presses F5 while browsing the /product/deleted action he will get 404. So basically what you are trying to do is bad design and I would recommend you avoiding it.


text:
Q: Adicionar meses a uma data javascript Eu possuo um campo que recebe uma data, a partir dessa data ele deve somar 1 mês

//Funcao das datas
function addData() {

//Pegar data Atual para somar
var currentDate = new Date();

//pegar data atual para exibir
var currentDate1 = new Date();

//Capturar Quantidade de meses
var meses = "1";
//Parse Int dos meses
var a = parseInt(meses);

//Adicionar meses
currentDate.setMonth(currentDate.getMonth()+a);

//Trazer data Atual
currentDate1.setDate(currentDate1.getDate());

//Exibir data Atual
document.getElementById('data').value = currentDate1.toLocaleDateString();

//Exibir a data ja atualizada
document.getElementById('dataAtualizada').value = currentDate.toLocaleDateString();

}

Data
<input type="text" id="data" value="">

Data Atualizada
<input type="text" id="dataAtualizada" value="">

<input type="button" onclick="addData()" value="Calc">

Eu peguei um código que adiciona mas a partir da data atual, eu preciso que ele capture a data que estiver no campo "text" e não a atual.
Exemplo existe um campo "text" com a seguinte data
Data
10/10/2018
Data atualizada
10/11/2018

A: Foi criado uma função para converter as datas:

function parseDate(texto) {
  let dataDigitadaSplit = texto.split("/");

  let dia = dataDigitadaSplit[0];
  let mes = dataDigitadaSplit[1];
  let ano = dataDigitadaSplit[2];

  if (ano.length < 4 && parseInt(ano) < 50) {
    ano = "20" + ano;
  } else if (ano.length < 4 && parseInt(ano) >= 50) {
    ano = "19" + ano;
  }
  ano = parseInt(ano);
  mes = mes - 1;

  return new Date(ano, mes, dia);
}

//Funcao das datas
function addData() {

  var dataDigitada = document.getElementById('data').value;

  //Pegar data Atual para somar
  var currentDate =parseDate(dataDigitada);

  //pegar data atual para exibir
  var currentDate1 = new Date();

  //Capturar Quantidade de meses
  var meses = "1";
  //Parse Int dos meses
  var a = parseInt(meses);

  //Adicionar meses
  currentDate.setMonth(currentDate.getMonth() + a);

  //Trazer data Atual
  currentDate1.setDate(currentDate1.getDate());

  //Exibir data Atual
  document.getElementById('data').value = currentDate1.toLocaleDateString();

  //Exibir a data ja atualizada
  document.getElementById('dataAtualizada').value = currentDate.toLocaleDateString();

}

Data
<input type="text" id="data" value="">

Data Atualizada
<input type="text" id="dataAtualizada" value="">

<input type="button" onclick="addData()" value="Calc">


text:
Q: Apache 2.4.12 Redirect Wordpress subfolder to another server ip address I am running wordpress inside the laravel public folder which acts as the root of my site. How do I redirect to another server ip address i.e. (xx.xx.xx.xxx) when one accesses the following subfolder: example.com/forum
The other server runs nginx with the forum as the only site.
Here is my apache vhost configuration for the site:
/etc/apache2/sites-available/example.conf
<VirtualHost *:80>
   ServerName example.com
   ServerAdmin me@example.com

   DocumentRoot /var/www/example

   RewriteEngine on
   ProxyRequests off

   #Redirect all HTTP requests to HTTPS
   RewriteCond %{SERVER_PORT} 80
   RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]

   #Redirect forum subdirectory requests to forum server
   RewriteRule ^/forum$ https://example.com/forum/ [R] [L]
   RewriteRule ^/forum/(.*) http://xx.xx.xx.xxx/$1 [P]

   <Directory /var/www/example>
     AllowOverride all
   </Directory>
</VirtualHost>

Application .htaccess
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On
    RewriteBase /

    # Redirect Trailing Slashes...
    RewriteCond %{REQUEST_URI} ^/(live|api|auth|_debugbar)$
    RewriteRule ^(.*[^/])$ /$1/ [L,R=301]

    RewriteCond %{REQUEST_URI} ^/(live|api|auth|_debugbar)/.*
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ laravel.php [L]

    # Handle Front Controller...
    RewriteRule ^index\.php$ - [L]

    #admin panel route
    RewriteRule ^([_0-9a-zA-Z-]+/)?admin-panel/(.*) $1wp-admin/$2?%{QUERY_STRING} [L]
    RewriteRule ^login(.*) wp-login\.php/$1?%{QUERY_STRING} [L]

    # uploaded files
    RewriteRule ^([_0-9a-zA-Z-]+/)?files/(.+) wp-includes/ms-files.php?file=$2 [L]

    # add a trailing slash to /wp-admin
    RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]
    RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
    RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
    RewriteRule . index.php [L]
</IfModule>

A: Easiest way would be to add:
Redirect permanent /forum http://otherserver

to your apache vhost config, or to add:
RewriteRule ^/forum(.*)$ http://otherserver/$1 [R=301,NC,L]

to your .htaccess.


text:
Q: Auto rotate issues in iPhone (portrait to landscape) I want my iphone to autoscale my website on rotation.
when I use this line of code it works:
<meta name="viewport" content="height=device-height, width=device-width, minimum-scale=1.0, user-scalable=yes|no" />

But the problem is that it activates both of my CSS for portrait and lanscape even though it should activate in landscape mode only one:
<link rel="stylesheet" media="screen and (min-device-width : 320px) and (max-device-width : 480px)" type="text/css" href="css/mobileStyles.css?<?php echo date('l jS \of F Y h:i:s A'); ?>">
<link rel="stylesheet" media="screen and (max-width : 320px)" type="text/css" href="css/mobilePortraitStyles.css?<?php echo date('l jS \of F Y h:i:s A'); ?>">

When I use this line instead of the meta above the css works right but no autoscale on rotation:
 <meta name="viewport" content="width=device-width, initial-scale=1.0">

What is the problem? What should I do?
Besides the meta line above I have these lines as well:
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="apple-mobile-web-app-capable" content="yes"/>

I test that on iPhone 4 (using iOS5)

A: Have you tried using the orientation keyword in your media queries? e.g.
<link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css">
<link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css">

A: The issue with no auto scale on rotation is an iOS bug.  Setting the max scale in the viewport seems to fix it but actually introduces as number of other issues - as you are seeing here it does not resize the viewport so does not trigger the media queries.
You might want to take a look at the workaround.


text:
Q: Bookdown PDF Book Font Change I'm using Bookdown to generate an ePub and a PDF of a book I'm writing. The book is generating fine, but I am trying to make a change to the font for the PDF from a serif font to a sans serif font. I tried what was listed in this StackOverflow post but it didn't work for me. Here are the contents of my preamble.tex file:
\usepackage{fontspec}
\setmainfont{Arial} # also have tried sansfont and arial, which I've seen in other places

and the contents of the _output.yml file:
bookdown::pdf_book:
  pandoc_args: --listings
  includes:
    in_header: preamble.tex
  latex_engine: xelatex # with this line, I get an error that the font can't be found; if I remove it, then the error doesn't show up and the font is still the default one

As far as I can tell, this should work, but it hasn't so far. Any suggestions on what to do to change the font?


text:
Q: How to get hidden form from task bar to front in C# winform? From class I am doing it from a class, because I've got code to make it so only one instance can work. I've seen lots of forums and just cannot figure it out. I've tried all sorts of methods like Application.OpenForms etc, nothing is working. The last form which was closed will be hidden in the taskbar. I just want to be able to bring that hidden form.
namespace EncryptionDecryption
{
    static class Program
    {

        /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        bool instanceCountOne = false;

        using (Mutex mtex = new Mutex(true, "MyRunningApp", out instanceCountOne))
        {
            if (instanceCountOne)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Login("", ""));
                mtex.ReleaseMutex();
            }
            else
            {

                MessageBox.Show("An instance of this application is already running in the taskbar", "Note");
                mtex.ReleaseMutex();

                Environment.GetCommandLineArgs();

                //Trying to pass the loggedinusername and role to new instance of the program so dont have to sign in again...
            }
        }

    }
}

A: Instead of using the above I used this which plays with threads to make sure I only have one instance and it will open that one instance only with new parameters to! Which i really needed for my next step!
https://social.msdn.microsoft.com/Forums/vstudio/en-US/a5bcfc8a-bf69-4bbc-923d-f30f9ecf5f64/single-instance-application?forum=csharpgeneral


text:
Q: How to actualize Django Template with get_context_data I need your help in order to know How I can actualize my Django template from get_context_data.
I have this class in my view :
class IdentitySocieteResumeView(LoginRequiredMixin,TemplateView) :

    template_name = 'Identity_Societe_Resume.html'
    model = Societe

    def get_context_data(self, **kwargs) :

        context_data = super(IdentitySocieteResumeView, self).get_context_data(**kwargs)

        id = self.kwargs['id']
        societe = get_object_or_404(Societe, pk=id)

        obj = Societe.objects.filter(Nom=societe.Nom, SIRET=societe.SIRET, SIREN=societe.SIREN, Ville=societe.Ville)

        if obj:
            sc_obj = obj[0]

            NIU = lib.Individu_Recherche.NIUGeneratorSociete(ModelBase=societe)

            societe.NumeroIdentification = NIU
            societe.save()

            context_data['queryset'] = obj

        return context_data

And this important function in lib.Individu_Recherche :
def NIUGeneratorSociete(ModelBase) :

    create_year_temp = str(ModelBase.Creation.year)
    create_year_temp2 = str(create_year_temp.split(" "))
    create_year = create_year_temp2[4] + create_year_temp2[5]

    ''' A process which let to generate NumeroIdentification '''

    NumeroIdentification = force_text('%s-%s%s-%s-%s-%s' % ('E', create_year, create_month, create_city, key, create_country_id))

    return NumeroIdentification

Part of my template :
{% block content %}

    {% for societe in queryset %}

        Votre société porte le numéro :  {{ societe.id}}

        N° identification attribué : {{societe.NumeroIdentification}}

    {% endfor %}
{% endblock %}

I'm sure my template is loaded before to execute this function and I get in my template NumeroIdentification = None but in my database this field is well-filled.
My question is :  How I can display my variable NumeroIdentification with the good value in my template (value stored in my database) instead of None ?
If I press Cmd + R (MacOS Actualize), NumeroIdentification won't be None but a different value. I would like to get this value in my template the first time.
It's pretty easy with FBV, but with CBV I don't overcome to make it
EDIT :
I add my function NIUGeneratorSociete :
def NIUGeneratorSociete(ModelBase) :

    create_year_temp = str(ModelBase.Creation.year)
    create_year_temp2 = str(create_year_temp.split(" "))
    create_year = create_year_temp2[4] + create_year_temp2[5]

    create_month_temp = ModelBase.Creation.month
    if len(str(create_month_temp)) == 1 :
        create_month = '0' + str(create_month_temp)
    else :
        create_month = create_month_temp

    create_city = Villes[ModelBase.Ville]

    key_temp = randint(0,999999)
    if len(str(key_temp)) == 1 :
        key = '00000' + str(key_temp)
    elif len(str(key_temp)) == 2 :
        key = '0000' + str(key_temp)
    elif len(str(key_temp)) == 3 :
        key = '000' + str(key_temp)
    elif len(str(key_temp)) == 4 :
        key = '00' + str(key_temp)
    elif len(str(key_temp)) == 5 :
        key = '0' + str(key_temp)
    else :
        key = key_temp

    create_country = ModelBase.Pays
    create_country_id = None
    if create_country == "CG" :
        create_country_id = 1
    else :
        create_country_id = 2

    NumeroIdentification = force_text('%s-%s%s-%s-%s-%s' % ('E', create_year, create_month, create_city, key, create_country_id))

    return NumeroIdentification

A: Unfortunately, this code is all kinds of confused. You're getting the same object in multiple different ways, and updating one copy but expecting the others to reflect the change.
You first get the relevant object as societe. Then for some reason you do another query on that model with all the fields of that object, to get a queryset consisting of one object. Then you do some manipulation of the original object and save it, but don't pass it to the context; instead you pass the queryset.
Your code can be simplified to just this:
def get_context_data(self, **kwargs) :

    context_data = super(IdentitySocieteResumeView, self).get_context_data(**kwargs)

    id = self.kwargs['id']
    societe = get_object_or_404(Societe, pk=id)

    NIU = lib.Individu_Recherche.NIUGeneratorSociete(societe)
    societe.NumeroIdentification = NIU
    societe.save()

    context_data['societe'] = societe

    return context_data

and the template:
{% block content %}

        Votre société porte le numéro :  {{ societe.id}}

        N° identification attribué : {{societe.NumeroIdentification}}

{% endblock %}

There are also some strange things going on in your library function. one is that you pass the object as the parameter ModelBase; although it doesn't matter what you call it, ModelBase is a class, but your parameter is an instance of your Societe class. You should call things what they are.
I can't correct that function though as it is clearly incomplete; all of create_month, create_city, key, create_country_id are undefined.
Finally, you should consider if any of this is appropriate. The update function is called from get_context_data in a normal GET request of your page; it would be very surprising for an object to be updated like this on a GET. Really this should be done on a POST only.

A: Lots of weird things going on here.
After societe = get_object_or_404(Societe, pk=id) you will have a Societe instance (or 404). You then filter Societe to get a list of objects that have the same properties at the instance you already received, and then fetch the first one of those. Why not just obj = get_object_or_404(Societe, pk=id) and skip the rest?
You then mix obj, societe and sc_obj. Your actions on one of them will be lost on the others until you fetch them again, which is probably why this works on refresh. Might be helpful to see your Societe model to confirm though.


text:
Q: how to add text to the miniature list block I am creating a module for prestashop 1.7, and I would like to add a text inside this block but I do not know how to do it:

I do not know if to use a hook, and which one!
edit : without modifying the tpl file of the theme
Thank's!

A: You can use this hook:
{hook h='displayProductPriceBlock' product=$product type="before_price"}

public function HookDisplayProductPriceBlock($params)
{
    if ($params['type'] == "before_price") {
        return 'TEXT'; // or return TPL file
    }
}

UPDATE:
On your module, you just need to register "displayProductPriceBlock" hook during installation process and add above function to yourmodule.php file.


text:
Q: Trace to Opera Dragonfly I am using Opera on a Windows PC and developing for a device. I can telnet into the device and manually run the browser which gives me the browser output.
Is it possible to trace messages into both Dragonfly and the Opera console? I can see a window.alert() message show up in the console, but I would also like to trace messages for simpler debugging and status tracking both within Dragonfly on PC and Opera on the device.

A: function debug(text) {
  ((window.console && console.log) ||
   (window.opera && opera.postError) ||
   window.alert).call(this, text);
}

I'm not positive this will solve your problems (I don't have much experience with Dragonfly) but it seems that opera.postError is the general API call for console logging on Opera.

A: console.log will work in Opera and Dragonfly from Opera 11. We added support for both the Console and the Command Line APIs from Firebug. See http://my.opera.com/dragonfly/blog/getting-opera-dragonfly-ready-for-opera-11/ for more information.


text:
Q: Angular2 Routing with url params Is there an elegant solution – in the name of DRY – to the following route definition?
{
   path: CalendarComponent.path, /* the path is 'calendar' */
   component: CalendarComponent,
   canActivate: [AuthGuard, EmployeeGuard],
   data: {
     navi: {
       at: 'main'
     },
     roles: {
       employeeOnly: true
     }
   },
},
{
   path: CalendarComponent.path + '/:urlString',
   component: CalendarComponent,
   canActivate: [AuthGuard, EmployeeGuard]
}

With the same CalendarComponent I want to be able to serve

*

*xyz.com/calendar

*xyz.com/calendar/2018-06-12
I tried to define this routing as follows:
{
   path: CalendarComponent.path,
   component: CalendarComponent,
   canActivate: [AuthGuard, EmployeeGuard],
   data: {
     navi: {
       at: 'main'
     },
     roles: {
       employeeOnly: true
     }
   },
   children: [
     {
        path: ':urlString',
        component: CalendarComponent
     }
   ]
}

but then it says Cannot read property 'component' of null @ router.js:3628, running into the same line of code as in Angular 5 TypeError: outlet is null / cannot read property 'component' of null while routing
Angular 5.1.0
Thanks.

A: Your set up should look more like this
{
  path: 'calendar/:urlstring', /* the path is 'calendar' */
  component: CalendarComponent,
  canActivate: [AuthGuard, EmployeeGuard],
  data: {
    navi: {
     at: 'main'
    },
    roles: {
      employeeOnly: true
    }
  },
}

with this you will be able to go to xyz.com/calendar/2018-2-4 but not xyz.com/calendar because you will need to have the urlstring for the route to work, if you want to have calendar and then also have calendar/2018-2-12 you will need to create two seperate components and have the urlstring component nested inside the calendar component in a router-outlet


text:
Q: Reset Path for iOS cover I've recently started using Path for iOS. I changed the Cover image used, the one behind the activity, but how on earth can I reset it back to what it was when I downloaded the app, I can only now choose from my photo library.

A: You can't. They say this in their documentation. They also say you can choose other images from the photographer who provided their stock cover art, but in fact you can't; you can leave the default image, change to one of your own, then change to another of your own, but that's all.

Once you change your initial cover photo, you cannot change it back to the original default cover, but you can change it to any other photo that you take or store in your photo library.

I think this new version of Path is quite nice, but there are some rough edges, and you just bumped into one of them.

A: You can opt to download nice Retina wallpapers for your iPhone and use it for your cover photo. Path doesn't (at least not in a very obvious way) lower the quality of photos uploaded to it. You can also check out fiftyfootshadows.net -- this is the person's blog who took the default cover photos of Path.


text:
Q: onReceive method of BroadcastReceiver does not get called I am using AlarmManager to create an alarm by playing a sound. To do this, I first create a PendingIntent, for which I have to create a class called AlarmReceiver, which extends BroadcastReceiver. In this new class, I override the onReceive method, in which I also start the sound. However, from what I've tested, the onReceive method is not even called from the MainActivity.
After some research, I found out that I should declare the receiver in the manifest file. Thus, I declare it, but it doesn't recognize the name of the class, AlarmReceiver, it shows it in red. I don't fully understand how to properly declare in the manifest file. I know there are other similar SO questions and I've checked them all, but I am still not able to get it work.
The code for the MainActivity is:
package com.example.alarmsound;
public class MainActivity extends AppCompatActivity {

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        final MediaPlayer mp = MediaPlayer.create(context, R.raw.music);
        Log.d("Music", "It went here.");
        mp.start();

        Button stop = (Button) findViewById(R.id.stopAlarm);
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.stop();
            }
        });
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_main);

    Calendar t = Calendar.getInstance();
    t.add(Calendar.SECOND, 5);

    Context context = this;
    AlarmManager alarmMgr;
    alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmMgr.set(AlarmManager.RTC_WAKEUP, t.getTimeInMillis(), pendingIntent);
}
}

And the declaration in Manifest is:
<receiver android:name="com.example.alarmsound.AlarmReceiver">
        <intent-filter>
            <action android:name="com.example.alarmsound.MainActivity" />
        </intent-filter>
</receiver>

I could also be doing something wrong in the MainActivity, even though I think I'm doing everything right there.

A: Change the first line of the receiver declaration to:
<receiver android:name="com.example.alarmsound.MainActivity$AlarmReceiver">. That should let Android detect your class through the manifest.
The $ symbol is used to reference inner classes in the Android Manifest.

A: Okay. So as you mentioned the the AlarmReceiver class cannot be recognized in the AndroidManifest.xml. So I tried it out in Android Studio and it seems the format should be something like this:
<receiver android:name=".MainActivity$AlarmReceiver">
            <intent-filter>
                <action android:name="com.example.alarmsound.MainActivity" />
            </intent-filter>
        </receiver>

Tried running the code but it returns an error where the app crashes. Anyways, I think that's a different concern now.


text: Q: How to override the style definitions in Reference.nb? Mathematica 11.1.0 introduces a new look to its documentation, which doesn't look good on my Windows machine. After some digging it turns out the styles are largely defined in Mathematica\SystemFiles\FrontEnd\StyleSheets\Wolfram\Reference.nb. But modifying this file directly triggers a beep. What's the recommended way to override these styles?


text:
Q: Default behavior of REST api. How multiple request to same api is handled I have a api(GET REST) developed using java & Quarkus. I want to understand the default mechanism on how this api handle the multiple requests to same api.  Is there any queuing mechanism used by default.? is there any multithreading used by default?
Please help to understand this.

A: Quarkus became popular for it's optimization of resources and benchmarks on heavy loaded systems. It will by default use 2 kind of different threads.

*

*I/O threads or otherwise called event-loop threads

*Worker threads
I/O threads or otherwise called event-loop threads. Those threads are responsible, among other things, for reading bytes from the HTTP request and writing bytes back to the HTTP response. The important here is that those threads are usually not blocked at all. You can see a simple of the functionality of those threads as illustrated in the following picture

The number of those I/o threads as described in documentation

The number if IO threads used to perform IO. This will be
automatically set to a reasonable value based on the number of CPU
cores if it is not provided. If this is set to a higher value than the
number of Vert.x event loops then it will be capped at the number of
event loops. In general this should be controlled by setting
quarkus.vertx.event-loops-pool-size, this setting should only be used
if you want to limit the number of HTTP io threads to a smaller number
than the total number of IO threads.

Worker threads. Here a pool of threads again are maintained by the system and the system assigns a worker thread to a execute some scheduled work on some request. Then this thread can be used from another thread to execute some other task. These threads normally take over long running tasks or blocking code.
The default number of these type of threads are 20 if not otherwise configured as indicated by documentation
So to sum up a request in Quarkus will be executed either by some I/O thread or some Worker thread and those threads will be shared between other requests too. An I/O thread will normally take over non blocking tasks that do not take long to be executed. A Worker thread will normally take over blocking tasks and long running processes.
Taking in consideration the above it makes sense that Quarkus will have configured much more Worker threads in the worker thread pool than I/O threads in the i/o thread pool.
What is very important to take from the above information is the following:
A worker thread will serve a specific request (ex request1) and if during this serve it get's blocked to do some I/O operation it will continue to wait for the I/O in order to complete the request it serves. When this request is finished the thread is able to move on and serve some other request (ex request2).
An I/O thread or event-loop thread will serve a specific request (ex request1) and if during this serve it get's blocked for some I/O operation which is needed for this request, it will pause this request, and continue to serve another request (ex request2). When the I/O of first request is completed the thread will return according to some algorithm that schedules the job again to request1 to continue from where it was left.
Now someone may question what is the case then, since usually every request requires some type of I/O operation then how can someone use I/O thread to have better performance. In that case the programmer has 2 choices when he declares the controller of quarkus to use I/O thread:

*

*Spawn manually inside the controller method which is declared to be I/O some other thread to do the blocking code block work while the outer thread that serves the request is of type I/O (read http request data, write http response). The manual thread can be of type worker inside some service layer. This is a bit complicated approach.

*Use some external library for I/O operations that's expected to work with the same approach that I/O threads work in quarkus. For example for database operations the I/O could be operated by the library hibernate-reactive. This way full benefits of I/O approach can be achieved.
Some side notes
Considering that we are in the java ecosystem it will be very useful to also mention that the above architecture and efficiency of resources is similar (not exactly same) with Spring Reactive (Web Flux).
But quarkus is based on Jax-Rs and will by default provide this architecture of efficient use of resources, independently of whether you write reactive code or not. When using Spring Boot however in order to have a similar efficiency with quarkus you have to use Spring Reactive (Web Flux).
In case you use the basic spring boot web, the architecture used will be of a single thread per incoming request. A specific thread in this case is not able to switch between different threads. It will need to complete some request in order to handle the next request.
Also in quarkus making a controller method execute from an I/O thread is as simple as placing an annotation @NonBlocking in that method. The same for an endpoint method that needs to be executed from a worker thread with @Blocking.
In Spring boot however switching from those 2 type of threads may mean switching from spring-boot-web to spring-boot-webflux and vice versa. Spring-boot-web has some support however now with servlet-3 to optimize it's approach, article with such optimization, but this requires some programming optimization and not an out of the box functionality.


text:
Q: For loops and dataframes, solving differential equation in R I am having trouble understanding for loops in R.
I want to kind of manually solve the equation "exp(kx)=k(x-t)+1" for x. I can't just get x on the left side of the equation alone, so I used ode to get numeric values for exp(k*x). I have estimates for the values of k and t.
library(deSolve)
library(graphics)
#estimated parameter value for k
k<-0.1
#function with ODE system
charnov_intercept=function(t,x,parameters){
  A=parameters[1];
  k=parameters[2];
  traveltime=parameters[3];
  odeVec=rep(0,1);
  odeVec[1]=k*(x[1]-t)+1;
  return(list(odeVec))
}
#give numeric values for exp(k*x)
numsol_expkT<-lsoda(y=c(0.1),times=seq(0,50,by=0.2),func=charnov_intercept,parms=c(30,0.1,-41))
df<-data.frame(numsol_expkT)

Now I would like to manually solve for x. I want to use a for loop applying ln(exp(k*x), these are the values that should be in df$X1 now) and then dividing this by k to obtain my values for x.
I would like to put all of these into new columns in my dataframe.
#ln
numsol_kT<-vector("double",ncol(df))
for(i in df$X1){
  numsol_kT[i]<-log(i) #achtung, log ist hier nicht log, sondern tatsächlich ln
  print(numsol_kT)
}

This doesn't work, however. R gives me 64 instead of 251 values. I'm brand new at R and have never worked with for loops or anything more than plots before, so I figure I'm doing something fundamentally wrong here.
The rest of the code goes:
#put vector as new col in df
df$numsol_kT<-numsol_kT[[2]]

#divide by k and save as new column
for(i in numsol_expkT[,2]){
  numsol_kT[i]<-log(numsol_expkT[i,2])
  print(numsol_kT)
}
df$Tpred_t<-numsol_kT[[2]]

I'm still at the very beginning, but if this doesn't work I can't really continue working on it.
Thanks a lot in advance!

A: Imagining I know nothing about the expected values here and picking up from numsol_expkT:
#give numeric values for exp(k*x)
numsol_expkT<-lsoda(y=c(0.1),times=seq(0,50,by=0.2),func=charnov_intercept,parms=c(30,0.1,-41))
df<-data.frame(numsol_expkT)
head(df)
  time        X1
1  0.0 0.1000000
2  0.2 0.3020202
3  0.4 0.5040812
4  0.6 0.7061839
5  0.8 0.9083289
6  1.0 1.1105173

ncol(df)
[1] 2
> nrow(df)
[1] 251

it is likely we now want nrow not ncol for numsol_kT
numsol_kT<-vector("double",nrow(df))
for(i in 1:length(df$X1)){
  numsol_kT[i]<-log(df$X1[i])

}
str(numsol_kT)
 num [1:251] -2.3026 -1.1973 -0.685 -0.3479 -0.0961 ...
df$numsol_kT <- numsol_kT

head(df)
  time        X1   numsol_kT
1  0.0 0.1000000 -2.30258509
2  0.2 0.3020202 -1.19726137
3  0.4 0.5040812 -0.68501788
4  0.6 0.7061839 -0.34787964

we can make a new receiver in df for next loop, made outside the loop as you did, but in this case a new df column
df$Tpred_t <- NA
for (i in 1:length(numsol_expkT[,2])) {
+ df$Tpred_t[i] <- log(numsol_expkT[i,2])
+ }
> head(df)
  time        X1   numsol_kT     Tpred_t
1  0.0 0.1000000 -2.30258509 -2.30258509
2  0.2 0.3020202 -1.19726137 -1.19726137
3  0.4 0.5040812 -0.68501788 -0.68501788
4  0.6 0.7061839 -0.34787964 -0.34787964
5  0.8 0.9083289 -0.09614875 -0.09614875
6  1.0 1.1105173  0.10482592  0.10482592

And as said, this is just about loop mechanics, not resultant values as I don't know what those should be. for is a counter, i is the count, 1:length( both where are we starting to count and how much.
You have to initialize 'receivers' outside the loop, as it is it's own environment, and gone when done, and you did initialize your receivers outside the loop (vector).


text:
Q: ASP.NET Membership Access to Network Resource I am using ASP.NET membership to control access to my application. Several pages in my application require read access to files on a network share (set up as an IIS Virtual Directory). Without membership, I just use impersonation to access the network share using a single predefined account. However, when using membership, how do I gain access to the network share with all of my "members"?

A: covered for a custom provider here, probably easy enough to do for yours as well.

A: Inherit built-in provider and implement impersonation inside


text:
Q: c# program works from cmd prompt but not run separately? I would post a snippet, but I honestly have no idea what part of my code could possibly be doing this. The program is sizable, I don't want to make you all wade through it. What kinds of things could possibly be the cause of this? Everything works perfectly when called from the command prompt: "readoo.exe". But when I click the exe in its file. . . "readoo.exe has encountered a problem and needs to close. . ."
this is intended to eventually be a scheduled task -> i'm worried, will it work?
i've never debugged, all i've ever used is notepad. I am learning, and feel that this strengthens my understanding of a project.
it crashes nearly immediately. there are no shortcuts, though the file paths are relative.
trying this method: shortcut -> properties -> shortcut -> Start In. I don't have a "shortcut" option
my program reads log files, parses, and creates 4 new files based on the found content
Microsoft Error Report says file not found. But how can this be? the files are there, albeit relative.

A: Take a copy of your project, and then start hacking bits out of it. When it no longer crashes, you've removed the bit causing the problem.
At what point does it fail when you double-click on it? Immediately, or only when you take a certain action?
You could also add a lot of logging to it, which could indicate where the problem is too.

A: This is probably looking for a dll that it can't find or is finding a different version from what it wants.
You could try Process Monitor or Process Explorer from sysinternals to see what dlls it loads when it does work and where it finds them.

A: Try putting a System.Diagnostics.Debugger.Break()call as the first thing in Main() and you'll be asked to attach a debugger - this should definitely show you what is different betweent the 2 invocations.

A: I would start with identifying what is different in the two methods of execution. Is there a shortcut modifying anything?

*

*The starting directory?

*The execution account?

*command line arguments?

A: If your application relies on some file that should be on the same path of that exe, that can occurr.
You will have to change the properties of the exe (or shortcut to the exe) to "Start In" the directory where your exe is. For a shortcut, right click on the shortcut -> properties -> shortcut -> Start In.
I guess that is what I think could be the cause.
EDIT: Add a Console.ReadLine towards the end of your code to make it pause for you to see any exception thrown. That should help when you run it using windows explorer.

A: There are 2 things that it could be:

*

*The current directory could be different when you click on the program or run from the command prompt.

*The settings and path could be different when you click on the programe you are using the standard command prompt, are you opening the visual studio command prompt when you run the program from the prompt.

A: Put a try/catch around your code and output the exception message to the console in the catch block. That should give you some clues.


text:
Q: How disable blinking cursor in gnome-shell's terminal? Using gnome-shell, I want to disable the blinking cursor in the default Terminal. Yet cannot find anything in its profile setting to toggle the behavior.
How can I achieve that? I prefer a one-liner.

A: As pointed out by this blog post, you can disable the blinking cursor through a subshell:
gsettings set org.gnome.Terminal.Legacy.Profile:/org/gnome/terminal/legacy/profiles:/:$(gsettings get org.gnome.Terminal.ProfilesList default | tr -d \')/ cursor-blink-mode off


text:
Q: $_SERVER['REQUEST_URI'] details breakdown Let's say my request url:
http://google.com?asdgeez~user=USERNAME~hash=SECRET_TOKKEN

I wanna select data like $data[1], $data[2], $data[3]
It should look like:
Array
(
    [0] => http://google.com?asdgeez
    [1] => USERNAME
    [2] => SECRET_TOKKEN
)

So basically it needs to remove ~user= and ~hash= part.
For feature usage it helps me validate each value separately.
Any ideas how to do it ?

A: Well...you could try it like this:
 $data = preg_split('#~(:?\w+=)?#', $_SERVER['REQUEST_URI']);

A: Try using regexp:
$input = 'http://google.com?asdgeez~user=USERNAME~hash=SECRET_TOKKEN';
preg_match('/^(.*?)~\w+=(.*?)~\w+=(.*)$/', $input, $matches);

var_dump($matches);

/*
array(4) {
  [0]=>
  string(58) "http://google.com?asdgeez~user=USERNAME~hash=SECRET_TOKKEN"
  [1]=>
  string(25) "http://google.com?asdgeez"
  [2]=>
  string(8) "USERNAME"
  [3]=>
  string(13) "SECRET_TOKKEN"
}
*/

A: $uri = "http://google.com?asdgeez~user=USERNAME~hash=SECRET_TOKKEN";

$str1 = explode('~user=', $uri);
$str2 = explode('~hash=', $str1[1]);

$final = array_merge($str1[0], $str2[0], $str2[1]);


text:
Q: Fast algorithm for finding prime numbers? First of all - I checked a lot in this forum and I haven't found something fast enough.
I try to make a function that returns me the prime numbers in a specified range.
For example I did this function (in C#) using the sieve of Eratosthenes. I tried also Atkin's sieve but the Eratosthenes one runs faster (in my implementation):
public static void SetPrimesSieve(int Range)
    {
        Primes = new List<uint>();
        Primes.Add(2);
        int Half = (Range - 1) >> 1;
        BitArray Nums = new BitArray(Half, false);
        int Sqrt = (int)Math.Sqrt(Range);
        for (int i = 3, j; i <= Sqrt; )
        {
            for (j = ((i * i) >> 1) - 1; j < Half; j += i)
                Nums[j] = true;
            do
                i += 2;
            while (i <= Sqrt && Nums[(i >> 1) - 1]);
        }
        for (int i = 0; i < Half; ++i)
           if (!Nums[i])
                Primes.Add((uint)(i << 1) + 3);
    }

It runs about twice faster than codes & algorithms I found...
There's should be a faster way to find prime numbers, could you help me?

A: When searching around for algorithms on this topic (for project Euler) I don't remember finding anything faster. If speed is really the concern, have you thought about just storing the primes so you simply need to look it up?
EDIT: quick google search found this, confirming that the fastest method would be just to page the results and look them up as needed.
One more edit - you may find more information here, essentially a duplicate of this topic. Top post there states that atkin's sieve was faster than eras' as far as generating on the fly.

A: The fastest algorithm in my experience so far is the Sieve of Erathostenes with wheel factorization for 2, 3 and 5, where the primes among the remaining numbers are represented as bits in a byte array.  In Java on one core of my 3 year old Laptop it takes 23 seconds to compute the primes up to 1 billion.
With wheel factorization the Sieve of Atkin was about a factor of two slower, while with an ordinary BitSet it was about 30% faster.
See also this answer.

A: I did an algorithm that can find prime numbers from range 2-90 000 000 for 0.65 sec on I 350M-notebook, written in C .... you have to use bitwise operations and have "code" for recalculating index of your array to index of concrete bit you want. for example If you want folds of number 2, concrete bits will be for example ....10101000 ... so if you read from left ... you get index 4,6,8 ... thats it

A: Several comments.

*

*For speed, precompute then load from disk.  It's super fast.  I did it in Java long ago.

*Don't store as an array, store as a bitsequence for odd numbers.  Way more efficient on memory

*If your speed question is that you want this particular computation to run fast (you need to justify why you can't precompute and load it from disk) you need to code a better Atkin's sieve.  It is faster.  But only slightly.

*You haven't indicated the end use for these primes.  We may be missing something completely because you've not told us the application.  Tell us a sketch of the application and the answers will be targetted better for your context.

*Why on earth do you think something faster exists?  You haven't justified your hunch.  This is a very hard problem.  (that is to find something faster)

A: You can do better than that using the Sieve of Atkin, but it is quite tricky to implement it fast and correctly. A simple translation of the Wikipedia pseudo-code is probably not good enough.


text:
Q: How to remember credentials on android Web App? I designed an application for android (I used android studio), which actually has an embedded web site, which was made by me in php.
The first screen of the application is a login. I would like to know how I can do to make the system to remember the user name and password, as happens in most of the android applications.

A: You'll probably gonna need a CookieManager and CookieSyncManager to maintain sessions when making calls in your WebView.
check out the API reference here: http://developer.android.com/reference/android/webkit/CookieSyncManager.html

A: I think you cannot run a .PHP page on a WebView on android. PHP is server-side so it needs to have a server to interpretate and process .PHP files.
If your goal is to have your android app built with HTTP pages, I suggest you Phonegap / Cordova. Take a look. There are many examples which uses Cache/Built-in storage to store variables.


text:
Q: importing data from one excel sheet to another? I am having 2 datasheets in one excel file. i want to import complete columns from one datasheet to another.
Remember i have to import complete columns like column a, b, c etc.
Is there any way to do so without manually copying each and every cell in the datasheets?
Right now I copy one cell at a time, that too manually. And that is a very painful and non efficient method.
thanks!

A: To select an entire column, simply left-click on the letter of the column you want. To select multiple columns, click and drag over the appropriate columns. The other method is to select the top cell, then press Shift+Ctrl+[Down Arrow], which selects the last occupied row (or the very last row if there's no values in between).
That said, you may want to look up some Excel tutorials since this is pretty basic stuff. It'll boost your confidence and knowledge, and you may even be able to help others!


text:
Q: How to create a timer "count up" using jQuery Countdown plugin? i am trying to use the jQuery plugin countdown 2.1 to count the time up. I need to clock to start at 0 and count up one second at a time.
Here is what I have done
        $('#MasterBreakTimer').countdown(new Date(),
        {
                elapsed: true,
                strftime: '%H:%M:%S'
        });

but it is not displaying anything
How can I correctly implement a count up clock?

A: I figured it out.
I need to add an event to display the results like so
$('#MasterBreakTimer').countdown(new Date(),
{
        elapse: true,
        strftime: '%H:%M:%S'
}).on('update.countdown', function(event){
    $(this).html(event.strftime('<span>%H:%M:%S</span>') );
});


text:
Q: Use same row per thread from a CSV data set in JMeter I want to make a test plan in JMeter as follows:
I have a specific flow with a web server:
Req1
Reply for Req1
Req2
Reply for Req2
Req2
Reply for Req2
etc

I need to have these run as a single flow i.e. each thread executes this from start to finish (not Req1 and Req2 send by different threads).
I also need to send different parameters in each iteration so I used CSV data set.
Problem:
I need to send the same row from CSV for all the requests per thread.
For example:
If I have the following CSV:
john,A1111,engineer
bill,A2111,manager
mary,C1111,secretary

I need the first row to be send in all the flow from Req1 to the last request by thread 1 and the second row by thread 2 in all requests etc.
Is this possible? I tried adding the same CSV file to all my controllers but still does not work as expected.
Update:
What I am interested in is having each thread consume 1 row from the CSV file and "cache" that row for all requests in my flow.

A: The simplest way to implement your scenario is like the following:
Test Group
Number of Threads = N
    CSV Data Set Config
    Filename: ... (your csv-file here)
    Variable Names: name,id,position       // (as per your csv sample above)
    Delimiter: ,
    Recycle on EOF = True
    Stop Thread on EOF = False
    Sharing Mode = All threads
    Simple Controller  // that's optional: simply to group your requests flow
        Sampler 01     // use ${name}, ${id}, ${position} variables to refer extracted values
        Sampler 02
        ...
        Sampler X

*

*Number of Threads = N will start N threads;

*Sharing Mode = All threads or Sharing Mode = Current thread group will enforce each thread to read separate row from csv and then use extracted values in all the subsequent samplers;

*Recycle on EOF = True will recycle your csv if number of threads N > number of entries in csv.


text:
Q: is_single() works in plugin, not in theme? I'm attempting to move some code from a plugin over to my theme's functions.php file, but when I attempt to wrap it in the is_single() wrapper inside of functions.php, it never fires. What am I missing?
if (is_single()) {
    echo "hello world";
}

I can't get the echo to fire from any inside post page.
This has to be something insanely simple I'm overlooking.

A: All that I can think of is to verify that you are in fact on a single post page ( echo out an else conditional, make sure that you are actually hitting your block of code ).
if ( is_single() ) {
    echo 'Hello World, Is Single';
} else {
    echo 'Not Single';
}

Where exactly are you placing the code (Header, Body, Footer, which template file)?  Are you using any frameworks like Carrington ?


text:
Q: browser close event in GWT/GXT? Hi I am using EditableGrid. i have a requirement as below, when user edits any record in grid and moves away without saving, then i need to alert the user saying that he has some data to be saved. and user should be given yes/cancel options. currently i am using below code, but the problem below code is executed every time when browser is closed/refreshed/logoff. but that message should be displayed when there are changes to be saved in the grid.
Window.addWindowClosingHandler(new Window.ClosingHandler() {
            @Override
            public void onWindowClosing(ClosingEvent closingEvent) {
                closingEvent.setMessage("Closing? Really?, you have unsaved data. you will loose it.");
            }
        });

Thanks,
Salmon

A: I don't think I have understood your question correctly, but from provided code snippet, I can't see any checks, which would prevent the code of executing? So, what is the problem to check, if there are any changes in your model and only then setMessage into the event?


text:
Q: How to clear textarea on WYSIHTML5 <textarea class="textarea" id="actionplan" style="width: 100%; height: 100px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"></textarea>

I am using ADMIN LTE's editor which is WYSIHTML5 and I want to clear the textarea after submission. I've tried using:
$("#actionplan").val("");
$("#actionplan").html("");

but it still doesn't work.
What are the other ways for clearing the wysihtml5 textarea?

A: just ..
$("#actionplan").val('');

but ... refresh cache javascript or never work !!!
you can refresh from code
< script src="../js/index.js?v0001"></script >

... before ...
< script src="../js/index.js?v0002"></script >

...