text:
Q: Listview with Checkbox is checking more than one checkbox So I've been working on a app with a listview with checkbox's and I've noticed when I select a item say the first item on the list when I scroll down the first item after scrolling down a full page has the checkbox selected as well.  I have a feeling this is due to recyled views but I'm curious as to the solution for this.  I had tried adding a viewholder but this didn't fix the issue.  Just wondering what I'm missing.  Code for the getview on the adapter is below:
        public override Android.Views.View GetView(int position, Android.Views.View convertView, ViewGroup parent)
        {
            Android.Views.View view = convertView;
            if (view == null)
            {
                view = context.LayoutInflater.Inflate(Resource.Layout.GroupTimeTrackerTemplate, parent, false);
            }
            tblWorkers item = this[position];

            view.FindViewById<TextView>(Resource.Id.UserNameTextView).Text = this[position].nWorkerFirstname + " " + this[position].nWorkerLastname;
            view.FindViewById<TextView>(Resource.Id.StatusTextView).Text = this[position].nStatusShort;
            view.FindViewById<TextView>(Resource.Id.UserRoleTextView).Text = this[position].nTitle;
            CheckBox chkSelect = view.FindViewById<CheckBox>(Resource.Id.ChkSelect);
            chkSelect.Tag = item.nWorkerFirstname + " " + item.nWorkerLastname;

            chkSelect.SetOnCheckedChangeListener(null);
            chkSelect.SetOnCheckedChangeListener(new CheckChangeListener(this.context));
            return view;
        }

        private class CheckChangeListener : Java.Lang.Object, CompoundButton.IOnCheckedChangeListener
        {

            private Activity activity;

            public CheckChangeListener(Activity activity)
            {
                this.activity = activity;
            }

            public void OnCheckedChanged(CompoundButton buttonView, bool isChecked)
            {
                if (isChecked)
                {
                    string name = (string)buttonView.Tag;
                    string text = string.Format("{0} Checked.", name);
                    Toast.MakeText(this.activity, text, ToastLength.Short).Show();
                }
            }
        }

A: I ended up finding a solution that has a View Holder that works with my dynamic model data.  And this worked for me below is the solution!  The three main points are the business logic object having a bool to hold the item being checked and the view holder helping with performance, and lastly because of the recyling of the views you cannot reliably use the list[position] in the click event so I used a wrapper!
View Holder :
    private class MyViewHolder : Java.Lang.Object
    {
        public TextView txtName;
        public TextView txtStatus;
        public TextView txtTitle;
        public CheckBox chkItem;

    }

Adapter GetView :
    public override Android.Views.View GetView(int position, Android.Views.View convertView, ViewGroup parent)
    {

        var item = list[position];
        Android.Views.View view = convertView;
        MyViewHolder holder;
        if (convertView == null)
        {
            holder = new MyViewHolder();
            view = context.LayoutInflater.Inflate(Resource.Layout.GroupTimeTrackerTemplate, null);
            holder.chkItem = view.FindViewById<CheckBox>(Resource.Id.ChkSelect);
            holder.txtName = view.FindViewById<TextView>(Resource.Id.UserNameTextView);
            holder.txtStatus = view.FindViewById<TextView>(Resource.Id.StatusTextView);
            holder.txtTitle = view.FindViewById<TextView>(Resource.Id.UserRoleTextView);
            view.Tag = holder;
        }
        else
        {
            holder = view.Tag as MyViewHolder;

        }
        holder.chkItem.Checked = item.StatusSelected;
        if (holder.chkItem.Checked)
        {
            holder.chkItem.Enabled = false;
        }
        else
        {
            holder.chkItem.Enabled = true;
        }
        holder.chkItem.Tag = new MyWrapper<int>(position);
        holder.txtName.Text = item.nWorkerFirstname + " " + item.nWorkerLastname;
        holder.txtStatus.Text = item.nStatusShort;
        holder.txtTitle.Text = item.nTitle;
        holder.chkItem.Click -= HolderChkItemClick;
        holder.chkItem.Click += HolderChkItemClick;
        if (statoChk[position] == 0)
        {
            holder.chkItem.Checked = false;
        }
        else
        {
            holder.chkItem.Checked = true;
        }

        return view;
    }

Click Event for checkbox, Wrapper, and array :
    tblWorkers OrigSel = null;
    void HolderChkItemClick(object sender, EventArgs e)
    {
        var chk = sender as CheckBox;
        int pos = ((MyWrapper<int>)chk.Tag).value;
        tblWorkers selectedWorker = list[pos];
        if (Vm.SelectedWorker == null)
        {
            OrigSel = selectedWorker;
            IntentManager.Instance.OriginalSelectedWorker = OrigSel;
            Vm.GroupTimeTrackerStatusType = OrigSel.nStatusShort;
        }
        Vm.SelectedWorker = selectedWorker;
        if (chk.Checked)
        {
            if (selectedWorker.nStatusShort == OrigSel.nStatusShort)
            {
                statoChk[pos] = 1;
                Vm.GroupTimeList.Add(selectedWorker);
            }
            else
            {
                statoChk[pos] = 0;
                chk.Checked = false;
                Toast.MakeText(context, "Please Select Workers with the Same Time Status. Current Status : " + OrigSel.nStatusShort, ToastLength.Long).Show();
            }
        }
        else
        {
            statoChk[pos] = 0;
            Vm.GroupTimeList.Remove(selectedWorker);
            if (Vm.GroupTimeList.Count == 0)
            {
                Vm.SelectedWorker = null;
                OrigSel = null;
                IntentManager.Instance.OriginalSelectedWorker = null;
                Vm.GroupTimeTrackerStatusType = "";
            }
        }

    }

    public class MyWrapper<T> : Java.Lang.Object
    {
        private T _value;
        public MyWrapper(T managedValue)
        {
            _value = managedValue;
        }
        public T value { get { return _value; } }
    }

    int[] statoChk;
    public int[] StatoCheck
    {
        get { return statoChk; }
        set { statoChk = value; }
    }

A: While I don't personally have developed Android through Xamarin I have the Android knowledge to get you in the right direction.
As you correctly stated the rows in a ListView are recycled. The problem is that, when you are scrolling, the OnCheckedChange method is called and since its recycling the rows it passes in the position of the new row that its not selected, but since it has the same index as the one that was previously selected it changes its value.
For example if you check the box with index 5 and then scroll down, a new row becomes row with index 5 and so it changes its state.
This is a common problem on Android. To solve it, first you need a data structure to keep track of which rows are already checked by storing it in a map or a list.
Then in your GetView make sure that you set the checkbox state to the contents of that position.

A: @Ivan Alburquerque is right, is due to the fact that Android recycles the views in the list.You should always set the value of the checkbox on the GetView method based on the position of your datasource.
In order to avoid all this repetitive code that you are writing here I will suggest you to use a MVVM framework like MvvmCross (https://github.com/mvvmcross/mvvmcross) that does everything for you and the code that you will need to write will be a lot less.
Have fun.


text:
Q: Angular directive intended to resize itself to match it's parent throws $digest() iterations error http://plnkr.co/edit/IdJUCtLz41wkUsXPNvgK?p=preview
So I have a canvas directive, and I want the canvas to fill it's parent div. I tried to do it like
app.directive('paperBoard', function () {
    return {
      template: '<canvas></canvas>',
      replace: true,
      restrict: 'E',
      scope:true,
      link: function (scope, element, attrs) {
        var cv = element;
        var ctx = cv[0].getContext("2d");

        scope.boundsdim = function(){
            return {
                'width': element.closest('div').width(),
                'height': element.closest('div').height()
            }
        };

    scope.$watch(scope.boundsdim, function(nv,ov){
            ctx.canvas.width = nv.width;
            ctx.canvas.height = nv.height;
        });

      }
    };
  });

Problem is, this seems to go in some sort of infinite loop and angular throws an 10 $digest() iterations reached. aborting error. Any ideas how to fix it?

A: you can fix this issue with small changes to your CSS.

.test {
  display: block;
  border: 2px solid red;
  width: 300px;
  height: 300px;
}
paper-board {
  display: block;
  width: 100%;
  height: 100%;
  border: solid blue 2px;
}

see the result at http://plnkr.co/edit/kSUFP8kDoYDJw9apVZ9a?p=preview

A: Change your code from watching by reference to watching collection contents.
scope.$watchCollection(scope.boundsdim, function(nv,ov){
        console.log(nv);
        ctx.canvas.width = nv.width;
        ctx.canvas.height = nv.height-4;
    });

From the Docs:

*

*Watching by reference (scope.$watch (watchExpression, listener)) detects a change when the whole value returned by the watch expression switches to a new value. If the value is an array or an object, changes inside it are not detected. This is the most efficient strategy.

*Watching collection contents (scope.$watchCollection (watchExpression, listener)) detects changes that occur inside an array or an object: When items are added, removed, or reordered. The detection is shallow - it does not reach into nested collections. Watching collection contents is more expensive than watching by reference, because copies of the collection contents need to be maintained. However, the strategy attempts to minimize the amount of copying required.

-- AngularJS Developer Guide -- scope watch depths.
Your scope.boundsdim function returns a new object each time it is called. Since $watch watches by reference, it was calling the listener function everytime.
Also your listener function was increasing the height by 4 each time. Changing to ctx.canvas.height = nv.height-4; stabilized height changes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to use ChoicePrompt without validating choices? I would like to present the user with a series of choices, but also allow them to type in freeform text.  The Choice prompt will automatically reprompt until a choice or synonym is chosen.
The RecognizerOptions NoValue and/or NoAction appear to be related to this, but I haven't been able to find good documentation on them.  Setting them to true doesn't work.
AddDialog(new ChoicePrompt(promptForChoice) { RecognizerOptions = new FindChoicesOptions() { NoValue = true, NoAction = true } });

I've also tried creating an "anything" validator that always returns true.
AddDialog(new ChoicePrompt(promptForChoice, validator: AnythingValidator.AnythingValidatorAsync) { RecognizerOptions = new FindChoicesOptions() { NoValue = true, NoAction = true } });

public static Task<bool> AnythingValidatorAsync(PromptValidatorContext<FoundChoice> promptContext, CancellationToken cancellationToken)
    {
        return Task.FromResult(true);
    }

This allows the prompt to exit, but the result is null.  I can go dig out what the user entered from the Context.Activity.Text but that doesn't seem like a very robust solution.
There seems to be something obvious I'm missing with PromptChoice

A: Choices work by hardcoding in the options the user needs to choose from. We can't implement freeform text in choices. What you can do is, add another choice "others" in the choice list and implement a waterfall to get the user input. Also, you can't use the RecognizerOptions as they are related to synonyms.


text:
Q: How to close a com.google.api.client.http.HttpResponse object properly I am trying to close a com.google.api.client.http.HttpResponse object, but I get the Eclipse error

Unhandled exception type IOException

on the line response.disconnect();
Here's a code example:
HttpRequest request = null;
HttpResponse response = null;

try {
    request = this.buildJsonApiRequest(apiUrl);
    response = this.execute(request);
    return response.parseAs(MyClass.class);
} catch (final IOException e) {
    throw new DaoException(e);
} finally {
    if (response != null) {
        response.disconnect();
    }
}

The code works without the finally block, but I am concerned about many response objects being opened and not closed. What is the proper way to do this?

A: You need to put the disconnect call within a try-catch block because according to Google API documentation that method could throw an IOException:
public void disconnect() throws IOException

Follow this link to learn more about it:
https://developers.google.com/api-client-library/java/google-http-java-client/reference/1.20.0/com/google/api/client/http/HttpResponse#disconnect()

A: This is in response to Eleazar Enrique answer that the disconnect needs to be within a try block. This is an example of how to possibly write it more elegantly and make it reusable.
You could create a handler class that implements autoCloseable then use try-with-resource
public class HttpResponseHandler implements AutoCloseable {
    private HttpResponse response;
    public HttpResponseHandler(HttpResponse response) {
        this.response = response;
    }
}

public <T> T parseAs(Class<T> clazz) throws IOException {
    return response.parseAs(clazz);
}

@Override
public void close() {
    if (response != null) {
        try {
            response.disconnect();
        } catch (IOException ex) {}
    }
}

then in your code it would be something like this
HttpRequest request = this.buildJsonApiRequest(apiUrl);

try (HttpResponseHandler handler = new HttpResponseHandler(this.execute(request)) {
    return handler.parseAs(MyClass.class);
} catch (final IOException e) {
    throw new DaoException(e);
}

The AutoCloseable will close the connection for you, so you wouldn't have to handle it in the finally block.


text:
Q: How to call a method from another class, which is in another .java file? The teacher gave us a .java file in which there is a method that I need to use in order to solve my question.
Here's the question :
Call the method countEnglishWords() given in the file SentenceChecker. This method takes as input a String and outputs the number of English words it contains.
My problem is that I do not know how to call a method which is in another class which is in another .java file!

A: you must ensure that the class & method you're trying to call have appropriate access modifiers (e.g. public). Then from your class' file, you may import the SentenceChecker class at the top.
String str = "Lorem ipsum dolor sit amet your mom";
SentenceChecker sc = new SentenceChecker();
sc.countEnglishWords(str); // this will call, you could assign any ret result to variable

edit:
you don't necessarily need import statement (i.e. files are in same dir).

*

*Put your sentence checker in some empty dir, say "/CheckerProgram"

*Create MySentenceCheckerCaller.java in same directory

*Edit MySentenceCheckerCaller.java to:
public class MySentenceCheckerCaller {
  public static void main(String[] args) {
     String str = "Lorem ipsum dolor sit amet your mom";
     SentenceChecker sc = new SentenceChecker();
     int wordCount = sc.countEnglishWords(str); // call method, assumes returns an int
     System.out.println("There are " + wordCount + " words in my string.");
   }
 }

*Compile MySentenceCheckerCaller.java and SentenceChecker.java

*Ensure that you have MySentenceCheckerCaller.class and SentenceChecker.class in program directory

*Run java MySentenceCheckerCaller in terminal


text:
Q: How to access Person or Group column in REST API Url I am trying to access Person or Group column using REST API, but it is giving an error "BAD URL". Can someone please help me with this ?
_api/web/lists/getByTitle('Plan')/getitems?$select=WRNo

Here WRNo is a person or group column name.

A: You can get it per item:
_api/web/lists/getByTitle('Plan')/items(<id of item>)?$select=WRNo/Title&$expand=WRNo/Id

or all:
_api/web/lists/getByTitle('Plan')/items?$select=WRNo/Title&$expand=WRNo/Id

A: You need to expand People or Group column to get the details associated with that column.
Get all items
 https://site-url/_api/web/Lists/GetByTitle('listname')/Items?$expand=WRNo&$select= WRNo/Title

Get specific item
https://site-url/_api/web/Lists/GetByTitle('listname')/Items(ItemID)?$expand=WRNo&$select= WRNo/Title

Where WRNo is the Person column Internal name.
Below are some available values other than Title to get from Person column with REST :
Title
Name
EMail
MobilePhone
SipAddress
Department
JobTitle
FirstName
LastName
WorkPhone
UserName
Office
ID
Modified
Created
ImnName
NameWithPicture
NameWithPictureAndDetails
ContentTypeDisp
I hope this helps.

A: you should use it like this
http://yourSite/_api/web/lists/getByTitle('Pages')/items?$select=Title,Id,Author/Title&$expand=Author

use expand to select people ou lookup fields
an example here


text:
Q: con.open has an error.I have a connection error an my code looks like this  if (lblevent.Text == Request.QueryString["name"])
 {
      string EventName = Request.QueryString["name"];
      const string SQL = "SELECT SMS FROM Event WHERE EventName = @EventName";

      using (SqlConnection con = new SqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true"))
      using (SqlCommand Command = new SqlCommand(SQL, con))
           Command.Parameters.Add("@EventName", EventName);
           {
                con.Open();//at here the "con" has an error it says:"'con' does not exist on current context."
           }
 }

Actually i have already declared an sqlconnection(con) int he above code but it does not read it. Please someone help.. Thanks

A: This is the problem:
using (SqlConnection con = new SqlConnection("..."))
using (SqlCommand Command = new SqlCommand(SQL, con))
 Command.Parameters.Add("@EventName", EventName);
{
    con.Open();
    ...
}

That's equivalent to:
using (SqlConnection con = new SqlConnection("..."))
{
    using (SqlCommand Command = new SqlCommand(SQL, con))
    {
        Command.Parameters.Add("@EventName", EventName);
    }
}
{
    con.Open();
    ...
}

At that point I hope it's obvious what's wrong - when you call con.Open you're no longer within the using statement body. You want:
using (SqlConnection con = new SqlConnection("..."))
using (SqlCommand Command = new SqlCommand(SQL, con))
{
    Command.Parameters.Add("@EventName", EventName);
    con.Open();
    ...
}

A: Maybe you should add brackets.
if (lblevent.Text == Request.QueryString["name"])
            {
       string EventName = Request.QueryString["name"];
                const string SQL = "SELECT SMS FROM Event WHERE EventName = @EventName";
                using (SqlConnection con = new SqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true"))
                  {
                   using (SqlCommand Command = new SqlCommand(SQL, con))
                     {
                      Command.Parameters.Add("@EventName", EventName);
                      con.Open();//at here the "con" has an error it says:"'con' does not exist on current context."
                     }
                  }
             }


text:
Q: Custom tool error Failed to generate code Why this error is appearing?  I was just setting some default values in a dataset designer...  its second time that this is appearing...
"Custom tool error Failed to generate code. Exception of type 'System.OutOfMemoryException' was thrown"

A: I just found a way to regenerate codes.
In Solution Explorer right click on your DataSet and click Run Custom Tool.
I do it after closing and reopening VS2010...
Hope this help you, if you faced the problem...
good luck

A: This happened to me when I changed the target framework from .net 4.5 to .net 4.8 on Visual Studio 2019.
For me was the Connections tag was looking for a global connection string or DatabaseProvinder that no longer existed.
If you don't need the connection anymore, You can just get rid of it.
Do that:
1- Right-click on the .xsd file chose open with and chose 'XML (Text) Editor', or another text editor that you prefer.

2- Delete de content of the Connections tag and closes it.

After that, you will have something like this:
...
<DataSource DefaultConnectionIndex="0" FunctionsComponentName="QueriesTableAdapter" Modifier="AutoLayout, AnsiClass, Class, Public" SchemaSerializationMode="IncludeSchema" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
    <Connections />
    <Tables />
    <Sources />
  </DataSource>
...

Reference / Similar question


text:
Q: Altering 6 images then preloading but the images are being pre loaded before they are altered I have 3 images of a horse/knight running. I am alternating them to make it look like its running. I am using GD to alter the colors of the knight/horse for the specific users chacter. I alter the images color then preload the 3 images. but by the time my program has altered the images they have already been preloaded. so i have to load the page twice for the correct colors of the knight.horse to apear. How do i fix this?
THE CODE is in the header. The function loadImage takes the base image and changes the color and saves it in the pic/#.gif file location. then the images are preloaded and a time is added on to the end so a new image is loaded and not a the image in the cache.
loadImage('pic/4.gif','pic/knightcolor0.gif',"1")

loadImage('pic/7.gif','pic/knightcolor0b.gif',"2")
loadImage('pic/5.gif','pic/knightcolor1.gif',"")
loadImage('pic/6.gif','pic/knightcolor2.gif',"")
loadImage('pic/8.gif','pic/knightcolor1R.gif',"")
loadImage('pic/9.gif','pic/knightcolor2R.gif',"")

img1 = new Image();
img1.src = "pic/4.gif?t="+new Date().getTime()
img2 = new Image();
img2.src =  "pic/5.gif?t="+new Date().getTime()
img3 = new Image();
img3.src =  "pic/6.gif?t="+new Date().getTime()
img4 = new Image();
img4.src = "pic/7.gif?t="+new Date().getTime()
img5 = new Image();
img5.src =  "pic/8.gif?t="+new Date().getTime()
img6 = new Image();
img6.src =  "pic/9.gif?t="+new Date().getTime()

pls help Ive tried a lot of things to fix this been working on it for a week now and cant figure it out ughhhhhh!

A: Preloading won't do you any good if it's calling an image that you don't want yet. If you set up the preload as a callback to the loadImage function, it won't execute until the right image is available.
Alternatively, could you narrow the choices of color? It's not inconceivable, in a situation like this, to have those images already prepared for use.


text:
Q: Django complex search with kwargs I am writing a view which searches my models db depending on search fields selected by the user. The basic code is something like:
def search(request):
if submit in request.POST:
    ...
    kwargs = {}
    if request.POST['field1']:
       kwargs['field1__icontains'] = request.POST['field1']

    if request.POST['field2']:
       kwargs['field2__icontains'] = request.POST['field2']
    ...
    results_list = Mymodel.objects.filter(**kwargs)
    ...

Of course this is fine if my query is all AND statements, but if I need to throw an OR in there - is it possible? For example if I needed field2__icontains = request.POST['field2'] OR field3__icontains = request.POST['field2']

A: To create an "OR" query you can use Q objects.
https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

A: Build up a Q() object instead of a dictionary as you work through your fields. Then you can and and or as you wish.
query = Q()
if request.POST['field1']:
    query &= Q(field1__icontains=request.POST['field1'])
if request.POST['field2'] and request.POST['field3']:
    query &= (Q(field2__icontains=request.POST['field2']) | Q(field3__icontains=request.POST['field3']))
results_list = MyModel.objects.filter(query)


text:
Q: Handle timeout when reading a remote file I am reading a remote file(xml) that is rendered by a webserver on the fly.Sometimes the webserver takes time to render the remote file.
Sometime there is issue with netowrk and remote url is not reachable
Am using the following code:
URL url = new URL(myurl);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
String strOutput = "";
System.out.println("start now");
//my code hangs after  priting start now    sometime.
//i think in.ready blocks the code flow.
if(in.ready() ){
  while ((inputLine = in.readLine()) != null) {
       strOutput = strOutput + inputLine;
  }
}

If input stream  is not ready i want my code to continue withoud blocking.How can i handle it?
How can i make sure that my code flow is never blocked indefinately?

A: You can set time out on the URL connection. See javadocs.
But you will have to get your stream slightly differently:
URLConnection con = url.openConnection();
con.setReadTimeout(timeout);
InputStream in = con.getInputStream();


text:
Q: Problem with Serializable, CompilerGenerated I recently had some problems with a code I was working with in Virtual Studio, below [Serializable, CompilerGenerated] line. I never did any work with that, so I don't quite understand it or how to solve the problem. The code:
    [Serializable, CompilerGenerated]
private sealed class <>c
{
    public static readonly BioFuelElement.<>c<>9 = new BioFuelElement.<>c();

internal string <.cctor>b__10_0(KeyValuePair<SimHashes, string> x) =>
    x.Value;

internal object <.cctor>b__10_1(KeyValuePair<SimHashes, string> x) =>
    x.Key;
}

The first problem already start with the "{", as it says it is an invalid token. Then it goes with <>c and everything that has the same character, stating that it don't exist in the actual context. I'm quite sure it has nothing to do with lib or references, since I'm using the original code references and files. I just need help to understand the situation and figure out a way to solve it.


text:
Q: ¿Cómo hacer que este código sea más eficiente? Estoy haciendo un código que determina el numero de subcadenas posibles en una cadena de texto. Las subcadenas pueden ser de todas las longitudes posibles, pero deben estar ordenadas de forma alfabética. La entrada consiste en un entero n que representa el numero de cadenas, un numero que determina la longitud de la cadena y la cadena de letras. La salida es el numero de subcadenas posibles ordenadas para cada una.
Ejemplo:

El código que ejecuté fue el siguiente:
#include <iostream>
using namespace std;

int main(){
    int T, j, k, N, i=0;
    cin>>T;
    while (i<T){
        cin >> N;
        int sub=N;
        char S[N];
        cin>>S;
        for (k=N;k>0;--k){
            for (j=0;j<k-1;++j){
                if(j==N && S[j]<=S[j+1]){
                    sub++;
                    S[j]=1;
                } else if (k==N){
                        S[j]=0;
                }else if(S[j]&&S[j+1]==1){
                    S[j]=S[j]&&S[j+1];
                    sub++;

                }else {
                    S[j]=0;
                }
            }
        }
        cout<<sub<<endl;
        i++;
    }

No obstante, el codigo debe ejecutarse en menos de 1 segundo, pero este se demora 1.48 segundos. ¿Cómo hago para hacerlo más eficiente?¿qué me recomiendan?

A: Una posible solución:
#include <iostream>

int main( ) {
  int count;
  int length;
  char *string = nullptr;

  std::cin >> count;

  for( int n = 0; n < count; ++n ) {
    std::cin >> length;

    string = new char[length + 1];
    string[length] = 0;

    std::cin >> string;

    const char *start = string;
    int sublen = 0;

    while( *start ) {
      ++sublen;
      const char *curr = start + 1;
      while( ( *curr ) && ( *curr >= *( curr - 1 ) ) ) {
        ++sublen;
        ++curr;
      }
      ++start;
    }

    std::cout << "Combinaciones: " << sublen << '\n';
    delete[] string;
  }

  return 0;
}

Me parecía divertido, así que no me baso en tu código; está escrito desde 0.
No lo he cronometrado, pero creo que tarda menos de 1 seg. en ejecutarse. Y si añadieramos un poco de gestión extra de memoria (o usáramos std::string, que reutiliza el buffer de memoria si le es posible, como te indican en los comentarios) aun tardaría menos :-)
Compilado con g++ -std=c++11 -Wall -Wextra -pedantic.


text:
Q: strange memcache behaviour on local apache server I'm currently having troubles about local deployment of my web service api. I'm using memcached with PHP Memcache extension. Here's the following behaviour;
I have a login function that firstly checks whether the user information is on memory with following code;
$cache = Memcacher::get_instance()->load( 'user.' . $email);

*

*if the cache exists, then it will return the variable $cache to be true.

*if the cache doesn't exist, then I'm saving it to the memory with following code;
$cache = Memcacher::get_instance()->save( 'user.' . $login['value']['email'], $login);
the parameter $login is an associative array that holds user info.
After saving it to the memory, I try to re-login. However, it doesn't hold the info before I save to memcached server 3-4 times.
After 3-4 login, I get the login information from cache successfully.
Can anyone explain me that strange behaviour ? Is there any memcached configuration variable to prevent this ?
NOTE : I'm flushing the memory with restarting memcached with sudo service memcached restart
on Ubuntu
NOTE : Memcacher is a custom module that uses PHP Memcache extension's set() and get() function
NOTE : Here's the source code of Memcacher

A: You are concatenating an array with a string. At points, it might not be true that $login is an array, therefore you will start receiving the information you have because the concatenation will work. But if it is an array, you will not be able to save the key in memcache. You will receive a notice, which i guess you ignore.


text:
Q: Efficient and accurate approximatiion of logarithm of binomial coefficients I am searching for an efficient and accurate way to approximate the logarithm of binomial coefficients since I have to deal with extremely large numbers in C++. Using Stirling approximation, I am able to compute values very fast:
$ln\binom{n}{k} \approx n\cdot ln(n) - m\cdot ln(k) - (n-k)\cdot ln(n-k) + \frac{1}{2}\cdot (ln(n) - ln(k) - ln(n-k) - ln(2\pi))$
However, the approximation is not very accurate. Since I am not very strong in numerical analysis, I would like to know if there is a better way to approximate $ln\binom{n}{k}$.
Any help would be much appreciated.

A: $$\binom{n}{k}=\frac{n!}{(n-k)! \, k!}=\frac{\Gamma(n+1)}{\Gamma(n-k+1)\,\Gamma(k+1)}$$
$$\log (\binom{n}{k})=\log(\Gamma(n+1))-\log(\Gamma(n-k+1))-\log(\Gamma(k+1))$$
Now, have a look here.


text:
Q: loggin uart from raspberry via terminal how can I keep continuing loggin the data from UART of Raspberry via SSH terminal ?
cat < /dev/ttyS0

this works but after a while "cat" ends and I have to relaunch the command via terminal


text:
Q: Log Normal Distribution within a Range I'm trying to figure out how to create a log-normal distribution in python within in range of days for a modelling project that I'm working on. I have researched this however; not really found anything that I can use. I do not have Mean and STD Dev just a range between 50 and 250.
I have some code that I have been playing with:
np.random.seed(42)
samples = np.random.lognormal(mean=0, sigma=1, size=500)
samples = samples * 26.4
samples

Using this I have been able to experiment with the mean, sigma and samples multiplier to get a distribution that roughly looks like what I'm after however; I'm wondering if there's a cleaner way using a range min - max.
Has anyone had a similar problem/need? Can you help with a code snippet please?
Thanks in advance!

A: I found this piece of code in an old file of mine. I don't know if it can help you...
from math import log
from random import random

def mylognorm(vmin, vmax):
    vrand = random()
    logratio = log(vmax) / log(vmin)
    power = ((logratio-1.) * vrand)+1.
    return vmin**power

vmin = 4.
vmax = 250.

print(mylognorm(vmin, vmax))


text:
Q: Trying to edit records with sql queries but only allows me to edit one record I am trying to edit records with sql queries but it only lets me edit one record. I try to update projectname and projectnr. When I try to update both records none of them gets updated.Whenever I try to update projectname it allows me to change it. Projectnr won't update when I try that one alone.

            include("dbconfig.php");
            // $connection = mysql_connect('localhost', 'root', '');
            // mysql_select_db('projectsync');

            if( isset($_GET['edit']))
            {
                $id = $_GET['edit'];

                /*$result = mysql_query("SELECT * FROM projecten WHERE projectnr='$id'");

                while($rows = mysql_fetch_array($result)){
                    $projectnr= $rows['projectnr'];
                    $projectnaam= $rows['projectnaam'];
                } */

                $query = "SELECT * FROM projecten WHERE projectnr='$id'";
                $projecten = $conn->prepare($query);

                try {
                    $projecten->execute(array());
                    $projecten->setFetchMode(PDO::FETCH_ASSOC);

                    foreach($projecten as $project){
                        $projectnr = $project['projectnr'];
                        // $email = $consultant['email'];
                        // $admin = $consultant['admin'];
                        $projectnaam = $project['projectnaam'];
                    }
                }
                catch(PDOException $e){
                echo "";
                }

                //$rows = mysql_fetch_array($result);

                //$res = $conn->prepare("SELECT * FROM klant WHERE klantnr='$id'");
                //$row = $res->fetch(PDO::FETCH_ASSOC);
            }

            if( isset($_POST['newProject']))
            {
                $newProject = $_POST['newProject'];
                $id    = $_POST['projectnr'];

                /*$sql = "UPDATE klant SET naam='$newUsername', admin= '$newAdmin', password= '$newPass', username= '$newName'
                WHERE klantnr='$id'";

                $row= mysql_fetch_array($res);
                $res   = mysql_query($sql)
                                            or die("Could not update".mysql_error());
                */

                try {
                    $query = "UPDATE projecten SET projectnaam='$newProject' WHERE projectnr='$id'";
                    $data = $conn->prepare($query);
                    $data->execute();
                    $row = $data->fetch(PDO::FETCH_ASSOC);
                }
                catch(PDOException $e) {
                    echo $e->getMessage();
                }
            }

            if(isset($_GET['delete']))
            {
                $id = $_GET['delete'];
                //$res= mysql_query("SELECT * FROM klant WHERE klantnr='$id'");
                //$row= mysql_fetch_array($res);

                $res = $conn->prepare("SELECT * FROM klant WHERE klantnr='$id'");
                $row = $res->fetch(PDO::FETCH_ASSOC);

                try {
                    include("dbconfig.php");

                    $sql = "DELETE FROM klant WHERE klantnr='$id'";

                    $conn->exec($sql);
                    echo "";
                    header("refresh: 0.4; url=manage.php");
                }
                catch(PDOException $e) {
                    echo $sql . "
" . $e->getMessage();
                }
            }

        ?>

        <!DOCTYPE html>

                <meta http-equiv="Content-Type"
                    content="text/html";
                    charset="UTF-8">
                    <title>Beheer gebruikers</title>
                    <link rel="stylesheet" href="css/styles.css">

                                    Admin

                                    Mijn Declaraties

                                    Declareren

                                    Projecten

                                    Declaraties

                                    Manage Users

                                    Logout

                            <form action="editp.php" method="POST" name="loginform" class="form-4" style="width: 300px">

Projectnr: <input type="text" name="projectnr" value="<?php echo $projectnr; ?>">

Projectnaam <input type="text" name="newProject" value="<?php echo $projectnaam; ?>">

<input type="submit" name="submitProject" value=" Update "/>

                            </form>


text:
Q: Query to reduce column length I'm new to PostgreSQL so sorry if I haven't explained myself clearly!
I've used the below query to find out the max character length of each column in my table. I now want to be able to shorten each column to the largest character length. Can anyone help?
SELECT
        MAX(char_length(gid)) as column1,
        MAX(char_length(column2)) as column2
FROM
        schema.table

The reason I want to do this I want to export to shapefiles and the file size is huge as the majority of the columns are set to 254.


text:
Q: How to open a new activity from a fragment using a switch case? Hi I am having problems with a switch case I have made. I want to open a new activity from a fragment.
This is my Switch:
@Override
public void onClick(View v)
{
    switch (v.getId())
    {
        //When the change password button is pressed...
        case R.id.btn_chg_password:
            showDialog();
            break;
        //When the Logout but is pressed...
        case R.id.btn_logout:
            logout();
            break;
        //When the write diary button is pressed...
        case R.id.btn_write:
            goToWriteDiary();
            break;
        //When the Read Diary button is pressed...
        case R.id.btn_read:
            Intent intent=new Intent(getActivity(), ReadFragment.class);
            startActivity(intent);
            break;
    }
}

And here is the Activity I wish to open with the Button = btn_read
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.ArrayList;
import java.util.Arrays;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ReadFragment extends AppCompatActivity
{
private RecyclerView recyclerView;
private ArrayList<Diary> data;
private DataAdapter adapter;
private SharedPreferences pref;

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

private void initViews()
{
    recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
    recyclerView.setHasFixedSize(true);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(layoutManager);

    String unique_id = pref.getString(Constants.UNIQUE_ID,"");
    loadJSON(unique_id);
}

private void loadJSON(String unique_id)
{
    Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();

    ServerRequest request = new ServerRequest();

    Diary diary = new Diary();
    diary.setUnique_id(unique_id);
    request.setOperation(Constants.CREATE_DIARY_OPERATION);

    RequestInterface requestInterface = retrofit.create(RequestInterface.class);
    Call<DiaryResponse> call = requestInterface.getDiary();
    call.enqueue(new Callback<DiaryResponse>()
    {
        @Override
        public void onResponse(Call<DiaryResponse> call, Response<DiaryResponse> response)
        {
            DiaryResponse diaryResponse = response.body();
            data = new ArrayList<>(Arrays.asList(diaryResponse.getDiary()));
            adapter = new DataAdapter(data);
            recyclerView.setAdapter(adapter);
        }

        @Override
        public void onFailure(Call<DiaryResponse> call, Throwable t)
        {
            Log.d("Error",t.getMessage());
        }
    });
}
}

Any help would be appreciated

A: EventBus is really helpful here. You can refer to my existing example to solve your problem.

A: Start Activity code is seem to perfect.
May be Null Pointer Exception at below line in code of ReadFragment Activity.
 String unique_id = pref.getString(Constants.UNIQUE_ID,"");

pref is not initialize, so initialize in onCreate Method.
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_read);
    pref= getSharedPreferences("your_pref_name", Context.MODE_PRIVATE);
    initViews();
}


text:
Q: Text input does not appear when uploading file using file input in any table row except for first row I have an application here: APPLICATION
Please follow steps below:

*

*Click on the Add Question button twice to append a 2 file inputs into the table below:

*By using the file input in TABLE ROW 1 ONLY upload 2 images (one at a time), every time an image is successfully uploaded, it displays the name of the uploaded file underneath and below the table it displays it's id in a text input.

*Now the problem is here, in TABLE ROW 2, upload a file. You realise after uploading is finished it does not display a text input underneath my table.
So my quesion is that if the user uploads a file in any file input except for the file input in the first table row, why will it not display the text input associated with those uploaded files?
Below is the code showing the file input and how it is appended into html table below, as well as showing the .hiddenimg div where it stores the text inputs:
Jquery appending file input form:
function GetFormImageCount(){
  return $('.imageuploadform').length + 1;
}

function insertQuestion(form) {

    var $tbody = $('#qandatbl_onthefly > tbody');
    var $tr = $("
");
    var $image = $("	");

    var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target_image' onsubmit='return imageClickHandler(this);' class='imageuploadform' >" +
        "
" +
        "Image File: <input name='fileImage' type='file' class='fileImage' />

" +
        "<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' />" +
        "
Loading...

" +
        "<input type='hidden' class='numimage' name='numimage' value='" + GetFormImageCount() + "' />" +
        "

" +
        "</form>");

    $image.append($fileImage);

    $tr.append($image);
    $tbody.append($tr);

}

HTML Form and table where file input form is appended to and where the text inputs are stored in the .hiddenimg div tag:
<form id="QandA" action="insertQuestion.php" method="post">

<input id="addQuestionBtn" name="addQuestion" type="button" value="Add Question" onClick="insertQuestion(this.form)" />

    Image

</form>

Below is code where it controls the upload buttons, the start of the upload and when the upload has finished.
Upload button Handler:
  function imageClickHandler(imageuploadform){
  if(imageValidation(imageuploadform)){
      window.lastUploadImageIndex = $('.imageuploadform').index(imageuploadform);
      return startImageUpload(imageuploadform);
  }
  return false;

Start Upload:
function startImageUpload(imageuploadform){

  $(imageuploadform).find('.imagef1_upload_process').show()
  $(imageuploadform).find('.imagef1_upload_form').hide();
  $(imageuploadform).find('.imagemsg').hide();
  sourceImageForm = imageuploadform;

      return true;
}

Upload finished:
 function stopImageUpload(success, imageID, imagefilename){

      var result = '';
      imagecounter++;

      if (success == 1){
         result = 'The file was uploaded successfully';
            $('.hiddenimg').eq(window.lastUploadImageIndex).append('<input type="text" name="imgid[]" id="'+imageID+'" value="' + imageID + '" />');
            $('.listImage').eq(window.lastUploadImageIndex).append('
' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" data-imageID="'+imageID+'"  data-image_file_name="' + imagefilename + '" value="'+imageID+'">Remove</button>

');
         }

  var _imagecounter = imagecounter;

$('.listImage').eq(window.lastUploadImageIndex).find(".deletefileimage").on("click", function(event) {
    jQuery.ajax("deleteimage.php?imagefilename=" + $(this).attr('data-image_file_name')).done(function(data) {
        $(".imagemsg" + _imagecounter).html(data);
    });

    var buttonid = $(this).attr('value');
    $(this).parent().remove();
     $("#"+ buttonid  +"").remove();
});

      return true;
}

A: the problem is in the stopImageUpload() function.
when you load the data and appending it to the placeholders you use the index of the current form the select the correct element to append to (like listImage)
if (success == 1){
     result = 'The file was uploaded successfully';
     $('.hiddenimg').eq(window.lastUploadImageIndex).append('<input type="text" name="imgid[]" id="'+imageID+'" value="' + imageID + '" />');
     $('.listImage').eq(window.lastUploadImageIndex).append('
' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" data-imageID="'+imageID+'"  data-image_file_name="' + imagefilename + '" value="'+imageID+'">Remove</button>

');
}

but the hiddenimg element is only one so your selector doesn't find any dom element where to append the new .
you code should be like this:
if (success == 1){
     result = 'The file was uploaded successfully';
     $('.hiddenimg').append('<input type="text" name="imgid[]" id="'+imageID+'" value="' + imageID + '" />');
     $('.listImage').eq(window.lastUploadImageIndex).append('
' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" data-imageID="'+imageID+'"  data-image_file_name="' + imagefilename + '" value="'+imageID+'">Remove</button>

');
}

btw, form inside form is bad practice Can you nest html forms?


text:
Q: Optimization of code / implementing "for" loop instead of long "if - else if - else" To say in brief about my QT GUI C++ program,
I have 4 labels, label1, label2, label3, label4 and a spinBox, comboBox and pushButton.
The functional (user operation logic) example,
if spinBox value = 1, on pushButton click, current comboBox index (text) = my_stringarray[0]
if spinBox value = 2, on pushButton click, current comboBox index (text) = my_stringarray[1]
if spinBox value = 3, on pushButton click, current comboBox index (text) = my_stringarray[2]
if spinBox value = 4, on pushButton click, current comboBox index (text) = my_stringarray[3]

now, the spinBox is bound 1-4 (i.e. in reference to the four qlabels label1 to 4) and the comboBox indices are "RED", "GREEN", "BLUE", "YELLOW"
the desired output logic is->
if my_stringarray[0] is RED set label1 color RED
if my_stringarray[0] is GREEN set label1 color GREEN
if my_stringarray[0] is BLUE set label1 color BLUE
if my_stringarray[0] is YELLOW set label1 color YELLOW
.
.
. and so on.

The same is also implemented by me by a rather long chain of if - else if - else commands which is getting the job done but seems not okay. So I am looking to implement a for loop solution for it, but cant make out how to initialize the loop parameters properly.
Any help / guideline with my rookie problem with the loop parameter initializing is highly appreciated.
Original code with "if - else if - else"

//for label1 color

if(settingsdialog->m_mystringarray[0]=="RED"
{
    ui->label1->setStyleSheet("QLabel{background-color: rgb(255, 0, 0)}");
    ui->label1->setText("I AM RED");
    qDebug()<<"label1 set RED";
}

else if(settingsdialog->m_mystringarray[0]=="GREEN"
{
    ui->label1->setStyleSheet("QLabel{background-color: rgb(0, 255, 0)}");
    ui->label1->setText("I AM GREEN");
    qDebug()<<"label1 set GREEN";
}

else if(settingsdialog->m_mystringarray[0]=="BLUE"
{
    ui->label1->setStyleSheet("QLabel{background-color: rgb(0, 0, 255)}");
    ui->label1->setText("I AM BLUE");
    qDebug()<<"label1 set BLUE";
}

and so on and on and on... as setting texts also involved, I think only a for loop can be my salvation...

A: You could use an std::map associating strings to numbers:
static std::map<std::string,int> mapcolors;

You'll initialize it e.g. with
mapcolors["RED"]= RedColor;
mapcolors["BLUE"] = BlueColor;

I would suggest to code in C++11 and upgrade to Qt5 (notably because C++11 is a huge win w.r.t. older versions of C++). You might even have the color be some enum class (then change the declaration of mapcolors accordingly)
BTW, you actual performance issue is perhaps the use at runtime of ui->label1->setStyleSheet("QLabel{background-color: rgb(0, 255, 0)}"); since the setStyleSheet has to "interpret" the "QLabel{background-color: rgb(0, 255, 0)}" string. It is probably not in a sequence of a dozen of if comparing strings (or perhaps even two hundreds of them!). Perhaps you should use some std::map<std::string,QStyle*> mapstyles instead, then
auto it = mapstyles.find(settingsdialog->m_mystringarray[0]);
if (it != mapstyles.end())
   ui->label1->setStyle(it->second);

You could even better associate both style and label text and have some std::map<std::string,std::pair<Style*,std::string>> maplook; etc... The second element of the pair being the string label (which might be some  QString instead of std::string)
With some efforts you could adapt this solution to the older Qt4 using C++98, but your code would be longer and less readable.


text:
Q: Why when change a dictionary from a list of dictionaries, the list also changes in Python? A code example:
>>> y = []
>>> x = {'num':1}
>>> y.append(x)
>>> x['num']=2
>>> x['new_num']=3
>>> y
[{'num': 2, 'new_num': 3}]

Why y is also changed when I change x? Does this logic also exist in other operations in Python?
A list of values don't have this phenomenon:
>>> y = []
>>> x = 1
>>> y.append(x)
>>> x += 1
y
[1]

A: Because when you append x to y, y[0] and x still refer to the same object, you can check that by doing:
>>> x is y[0]
True

You can see that both object share the same memory address.
If you want both to be different you need to do:
y.append(x.copy())

A: If you know the concept of "Call by value vs call by reference", your question has the same answer. I try to explain the difference between primitive value and reference in your two examples.
At first, you are creating an empty list [] and saving its memory address in the variable y. After that, you create a dictionary {'num':1} and save the memory address of that dictionary in the variable x. Then by running the y.append(x) statement, you are saving the saved dictionary address from x as a new element in the dictionary that is referenced by y.
So there is just one dictionary in the memory, but its address is saved in both variable x and the first element of the list that is referenced by y. Never mind that when you are referencing the dictionary you use the address that is stored in the variable x or in the first element of the list, you'll get the same result. So, there is no difference betweenx['num']=2 and y[0]['num']=2 and make the same result.
In your second code, you make a copy of the value 1 stored in the variable x as the first value of the list that is referenced by y. Copying the value doesn't have any similarity with copying the address, and when you change the 1 value stored in the variable x to 2, it doesn't make any changes in the 1 value that is stored in the first element of the array that is referenced by y.


text:
Q: Function in jQuery to loop over elements and show/hide? I have a string, I want to split it into a group of
 elements, create a function to show/hide each one on a delay, and then rerun the function if a user presses the button.
So far I take the string and split it into the result
 but my efforts to loop over them and show/hide each one on delay hasn't been successful.
Here's a fiddle:
HTML:

    Hello! Lorem ipsom dolor set amit.

<button>Run</button>

Js:
var words = $("span").text();
var split = words.split(" ");
for(var i = 0; i < split.length; i++) {
    $(".result").append("
" + split[i] + "
");
};

In short: I want it to look like:
<p1>.show(1000) -> <p1>.hide() <p2>.show(1000) -> <p2>.hide() <p3>.show(1000)...

A: Try using .queue() , .fadeIn() , .fadeOut()

var words = $("span").text(), result = $(".result")
, split = words.split(" ");
for (var i = 0; i < split.length; i++) {
  result.append("
 " + split[i] + "
");
};
$("button").click(function() {
  if (result.queue("cycle").length === 0) {
    result.queue("cycle", $.map($("> p", result), function(el, i) {
      return function(next) {
        $(el).fadeIn(1000, function() {
          $(this).fadeOut(next)
        })
      }
    })).dequeue("cycle")
  }
})

  Hello! Lorem ipsom dolor set amit.

<button>Run</button>

A: A very simple way to do it with jQuery promises:

$('button').on('click', function() {
  $('.result').empty(); //reset
  var words = $("span").text();
  var split = words.split(" ");
  for (var i = 0; i < split.length; i++) {
    var p = $("
" + split[i] + "
");
    p.appendTo('.result');
  };

  var p = $.Deferred().resolve().promise();
  $('.result p').each(function(i, par) {
    var $par = $(par);
    p = p.then(function() {
      $par.show(500).delay(500).hide(500);
      return $par.promise();
    });
  });
});
.result {
  height: 20px;
  }

.result p {
  margin: 0px;
  display : none;
  }

  Hello! Lorem ipsom dolor set amit.

<button>Run</button>


text:
Q: Restrict wifi access during time periods I need to block all access to a Wi-Fi hotspot to all devices (that already have previously connected and to any new devices that will connect) within a certain time frame e.g 8:30-13:00 on Sundays. While only allow one computer to use the network and two or three Android devices.
The rest of the time anyone can connect.
I mean an easy way would be to change the password twice but I would rather want an automatic way.
Is there a way of using Windows 10 firewall to do this?
EDIT I forgot to mention I connect to a booster and the booster connects to a (Vodafone) Huawei HHG2500 router. So I'm actually not sure if applying settings to the router will help I would probably have to access the booster and see what features it provides?
Or a different approach while the computer is on only the first two devices that connect can connect and the rest are automatically blocked?
The main issue is that the connection lags so I need to prioritise bandwidth for the computer.


text:
Q: What Adapter for bean Object? I'm sending an bean Object from the first to the second View. Other times I use ArrayAdapter when I had an Array with data to show but this time I only have an bean Object that I want to show. What type of Adapter I must to use ?

A: You do not need to use any adapter, just pass the object itself. You can use the passed object in the activity directly, for setting the contents of the UI controls, for instance. You need adapters when you have a list of items. More information on this is provided on the class documentation of Adapter here: http://developer.android.com/reference/android/widget/Adapter.html


text:
Q: How to select which view is resized by the adjustResize android keyboard attribute I want a viewA to be resize by the keyboard and the viewB to be hidden when the keyboard appears : see the attached picture
In the manifest I used the following attribute : "adjustResize"
I saw some post about checking if the keyboard is shown and change the viewB visibility to "GONE" but it doesn't seems very good regarding the animation of the keyboard..
Does anyone have an idea to make it works ? A way to keek the viewB in the bottom hidden by the keyboard ?


text:
Q: DOMPDF background image looks sharp sometimes Im using DOMPDF to create a certificate so people can print it. Problem is that the background image sometimes looks sharp. And thats the thing sometimes looks nice , sometimes not and im not sure why.
My pdf html code is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

10

12

Jhon Doe

#4

Image can be found at http://weightlosssuccessoholics.com/pdf/30-Day-Goals-Certificate.jpg
And my pdf generator code is :
<?php

require_once("dompdf_config.inc.php");
 ob_start();

require("pdf.php");
$dompdf = new DOMPDF();

$dompdf->load_html(ob_get_clean());
$dompdf->set_paper(array(0,0,629.00,410.00),'portrait');
$dompdf->render();

$dompdf->stream();
?>

Anyone is running into the same problem? Its looks like a ramdom error and i cant figure out the reason. Thanks in advance for all your help

A: you can up the resolution using the following variable:
def("DOMPDF_DPI", 96);
in dompdf_config.inc.php
/**
 * Image DPI setting
 *
 * This setting determines the default DPI setting for images and fonts.  The
 * DPI may be overridden for inline images by explictly setting the
 * image's width & height style attributes (i.e. if the image's native
 * width is 600 pixels and you specify the image's width as 72 points,
 * the image will have a DPI of 600 in the rendered PDF.  The DPI of
 * background images can not be overridden and is controlled entirely
 * via this parameter.
 *
 * For the purposes of DOMPDF, pixels per inch (PPI) = dots per inch (DPI).
 * If a size in html is given as px (or without unit as image size),
 * this tells the corresponding size in pt.
 * This adjusts the relative sizes to be similar to the rendering of the
 * html page in a reference browser.
 *
 * In pdf, always 1 pt = 1/72 inch
 *
 * Rendering resolution of various browsers in px per inch:
 * Windows Firefox and Internet Explorer:
 *   SystemControl->Display properties->FontResolution: Default:96, largefonts:120, custom:?
 * Linux Firefox:
 *   about:config *resolution: Default:96
 *   (xorg screen dimension in mm and Desktop font dpi settings are ignored)
 *
 * Take care about extra font/image zoom factor of browser.
 *
 * In images,  size in pixel attribute, img css style, are overriding
 * the real image dimension in px for rendering.
 */


text:
Q: An expression or idiom to describe "magnifying" a news or an occurance How would you call the action of someone who hears a news, magnifies it and then transmits it to someone else which would resault in an untrue story about (somebody / an event) comparing the original one in the manner that the final telling bears only a scant resemblance to the original and  occasionally even no similarity?
Please consider this act sometimes, can be done just to draw the listener's attention or even habitually!
PS. I'm looking for a an expression / an idiom or even a saying or proverb to describe this action.

A: Idiomatically, if you do that, you are blowing it out of proportion:

[The Free Dictionary]
blow (something) out of (all) proportion
  To make something seem more important, negative, or significant than it really is; to exaggerate something or focus unnecessary attention on something. I'm sure he didn't mean anything by that comment—don't blow it out of proportion. Of course she's mad at me because I didn't call her back—you can always count on my mom to blow something out of all proportion!


text:
Q: Setting up dual monitors Just installed a fresh copy of Maverick, and went from my two monitors working perfectly to broken in seconds.
As usual I configured the monitors in the display applet, this worked fine. I also hit Make Default which gave me no problems. I then restarted and the monitors had gone back to Mirror Screen. I changed them back again and hit Make Default which gave me a message about setting the Virtual Desktop resolution. After this any changes I make to the monitors give me the message "Please log out and back in again" - I've tried that and restarting but still cannot configure the monitor resolutions.
Any ideas on how I can revert this? Some searching indicates the problem's with xorg but I've no idea where to go further than this.
Here's the relevant lspci output:
01:00.0 VGA compatible controller: ATI Technologies Inc M92 [Mobility Radeon HD 4500 Series]

I tried extending the desktop using ATI's Catalyst tool but this still mirrored the screens. Does this mean the drivers aren't being used?

A: According to your edits:
you disabled the ATI drivers and it works automatically.
Problem solved, at least for now.

A: I was having issues with setting up my dual monitors as well. I had to go into my BIOS and set my default video adapter from Auto to PCI x16.


text:
Q: Databinding to an Object with a property that's a string array I can't seem to figure out how to get the actual value with a repeater.  The data is there but it just displays a bunch of System.String[] as the value in the repeater.  Basically, I have a NewsItem object.  In the NewsItem object there is a field called tags.  In the tags there is an array of strings for the tags.  I'm trying to create a tag cloud based on all of the newsitems returned. I'm able to get data to the repeater, I just can't seem to figure out what data is coming. Any direction would be appreciated.  I've been googling for hours.
repeater datasource:
rptTagCloud.DataSource = allnewsitems.Select(x => x.NewsItemTags).Distinct();

in repeater: <%# Container.DataItem %>


text:
Q: Запрос подписчиков Отправляю в коде запрос на сервер.
https://api.instagram.com/v1/users/{user-id}/follows?access_token={мой токен}

Работает только если просматривать самого себя, то есть писать вместо username self. Если ввести ссылку с self в браузере, то возвращается текст JSON, если же там будет user-id другого пользователя, то говорит, что страница недоступна: ссылка недействительна или же была удалена. В чем дело? Мне не хватает прав на просмотр? Как их тогда можно получить?

A: Дело в том, что видимо ваше приложение находится в режиме 'песочницы' https://www.instagram.com/developer/sandbox/ Вам доступны только ограниченные ф-ции API. Вы можете выслать инвайты в Ваше приложение ещё 10 пользователям и ставить "опыты" над ними(будут доступны все фунуции API). Для того, чтобы выйти из режима "песочницы" приложение должно быть одобрено. Отправить на рассмотрение - ManageClient - Edit - Go Live.


text:
Q: Java is unavailable for the hp loadrunner tutorial I am using the trial version of HP LoadRunner (v12).
On the flights page of the  tutorial
http://localhost:1080/WebTours/index.htm

I getting the error the Java is unavailable. Though I have installed the Java. The issue is around the departure and return dates. I have tried to use this tutorial using different browsers (IE11,FF,Chrome,Safari) but the problem is the same. I am using Windows 7 on 64 bit machine.
(IE11 could be of 32 bit but the rest of the browsers are 64 bit)

A: LoadRunner is a 32 bit product.  If you have 64 bit Java then you are out of luck.   Please see all installation notes regarding the use of LoadRunner in 64 bit environments.
There is no trial version of LoadRunner version 12.  There is a non expiring community edition, but there is no trial, trail rated, evaluation, POC, etc...   There are still training & production licenses available for purchase.


text:
Q: GenericJDBCException in HSQL I have an entity called ProdTransaction. I am saving two records of type ProdTransaction. Both the two inserts succeed when run independently. I mean
tranDAO.save(record1) //alone works
tranDAO.save(record2) //alone works

but together running them as
tranDAO.save(record1)
tranDAO.save(record2)

HSQL throws a GenericJDBCException error.
@Entity
@Table(name = "ProdTransaction")
public class ProdTransactionextends PersistentObject implements Serializable {
private static final long serialVersionUID = 1L;

@Embedded
private ProdTranPK id;

@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE)
@Column(name = "REC_ID")
private Long recId;

@Temporal(TemporalType.DATE)
private Date date1;

@Column(length = 1)
private String comment;
}

I have verified the data and it's all fine. When I run against HSQL I get:

GenericJDBCException: could not execute JDBC batch update.

But if I connect to my physical DB, and run with the same sequence, it works fine. What could be the problem in HSQL? I am using version 1.8.

A: HSQLDB batching bug was fixed, now it works ok. Problem is that if you have an error, such as a problem with your SQL statement etc, you'll only get a generic exception that doesn't really tell you anything. What I like to do is have a helper class that can execute SQL queries in batch mode and individually, and I switch to individual queries when I get weird errors from batch mode. Try that, maybe it's just a simple mistake in your SQL

A: It's also possible to disable batching in hibernate.  In the hibernate session configuration, set:
hibernate.jdbc.factory_class=org.hibernate.jdbc.NonBatchingBatcherFactory


text:
Q: How can i move the "camera" of the canvas in HTML? I'm making a 3D game which guides you across skyboxes, and what I need to do is for it to detect when the user presses a key, and move the camera that way (I'm fine with standard WASD).
How could I do this?
JavaScript:
var world = document.getElementById("boxDiv");
var x;
var y;

document.addEventListener('mousemove', function (e)
{
x = e.clientX;
y = e.clientY;
y = -y;
world.style.transform = "translateZ(600px) rotateX("+y+"deg) rotateY("+x+"deg)";
});

This code is for the skybox generation.

A: I think this is one of the best minimal reproducible examples on WASD controls on three.js

Kudos for the author Fyrestar
Relevant code is below:
// author: Fyrestar <info@mevedia.com>
var camera, scene, renderer, mesh, goal, keys, follow;

var time = 0;
var newPosition = new THREE.Vector3();
var matrix = new THREE.Matrix4();

var stop = 1;
var DEGTORAD = 0.01745327;
var temp = new THREE.Vector3;
var dir = new THREE.Vector3;
var a = new THREE.Vector3;
var b = new THREE.Vector3;
var coronaSafetyDistance = 0.3;
var velocity = 0.0;
var speed = 0.0;

init();
animate();

function init() {

    camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
    camera.position.set( 0, .3, 0 );

    scene = new THREE.Scene();
    camera.lookAt( scene.position );

    var geometry = new THREE.BoxBufferGeometry( 0.2, 0.2, 0.2 );
    var material = new THREE.MeshNormalMaterial();

    mesh = new THREE.Mesh( geometry, material );

    goal = new THREE.Object3D;
    follow = new THREE.Object3D;
    follow.position.z = -coronaSafetyDistance;
    mesh.add( follow );

    goal.add( camera );
    scene.add( mesh );

    var gridHelper = new THREE.GridHelper( 40, 40 );
    scene.add( gridHelper );

    scene.add( new THREE.AxesHelper() );

    renderer = new THREE.WebGLRenderer( { antialias: true } );
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

keys = {
    a: false,
    s: false,
    d: false,
    w: false
  };

  document.body.addEventListener( 'keydown', function(e) {

    const key = e.code.replace('Key', '').toLowerCase();
    if ( keys[ key ] !== undefined )
      keys[ key ] = true;

  });
  document.body.addEventListener( 'keyup', function(e) {

    const key = e.code.replace('Key', '').toLowerCase();
    if ( keys[ key ] !== undefined )
      keys[ key ] = false;

  });

}

function animate() {

    requestAnimationFrame( animate );

  speed = 0.0;

  if ( keys.w )
    speed = 0.01;
  else if ( keys.s )
    speed = -0.01;

  velocity += ( speed - velocity ) * .3;
  mesh.translateZ( velocity );

  if ( keys.a )
    mesh.rotateY(0.05);
  else if ( keys.d )
    mesh.rotateY(-0.05);

  a.lerp(mesh.position, 0.4);
  b.copy(goal.position);

    dir.copy( a ).sub( b ).normalize();
    const dis = a.distanceTo( b ) - coronaSafetyDistance;
    goal.position.addScaledVector( dir, dis );
    goal.position.lerp(temp, 0.02);
    temp.setFromMatrixPosition(follow.matrixWorld);

    camera.lookAt( mesh.position );

    renderer.render( scene, camera );

}


text:
Q: Equivalent formulations of finitistic Szemerédi's theorem I've been reading about Szemerédi's theorem recently and I'm stuck at its equivalent formulations, namely the ones called finitistic.
There are in fact two versions of it that I have seen and I'm not sure why one of them is equivalent to Szemerédi's theorem (or to another one). I might be missing something trivial, but here it is:
On this page for instance: https://joelmoreira.wordpress.com/2014/02/04/szemeredis-theorem-part-i-equivalent-formulations/ we can see the version whose equivalence with Szemerédi's theorem I can understand. It states the following:
Let $\delta>$ and $k\in\mathbb{N}$. Then there exists a number $N=N(\delta,k)$ such that for every $n\geq N$ and every $A\subset[n]$ with $|A|>\delta n$ there exists a $k$-term arithmetic progression in $A$.
The version given on Wikipedia page (https://en.m.wikipedia.org/wiki/Szemer%C3%A9di%27s_theorem) about Szemerédi's theorem differs slightly, however:
Let $\delta>$ and $k\in\mathbb{N}$. Then there exists a number $N=N(\delta,k)$ such that for every $A\subset[N]$ with $|A|>\delta N$ there exists a $k$-term arithmetic progression in $A$.
It's obvious that the first one implys the the second one. On the contrary, I fail to understand the opposite implication. How could we use the second statement to prove that there is sufficiently large $N$ such that $k$-term arithmetic progression exists when we surpass it? Why wouldn't there be a "gap" between the first and the second $N$ where the arithmetic progression doesn't exist for every subset.


text:
Q: About the solutions of a PDE I would like to know how the following statement is proved. I do not have any reference, buy I want to know where this come from because it is used in a proof that I am working with and I am not familiar with PDE's. Maybe is an extension of a real PDE's result, but I do not know.

Let $g,h:U\subset\mathbb{C}^2\to \mathbb{C}$ be two analytic
  functions, where $U$ is an open subset of $\mathbb{C}^2$ that contains
  $z_0:=(x_0,y_0)\in\mathbb{R}^2\subset\mathbb{C}^2$.
Then, the solutions of the equation \begin{equation}
     g(x,y)\frac{\partial f}{\partial x} + h(x,y)\frac{\partial f}{\partial y} = 0\end{equation} are the functions $f$ that are constant
  on the solutions of \begin{equation}
     \frac{dy}{dx} = \frac{h}{g}. \end{equation}
Moreover, such functions are determined by their values on any
  transversal to the solutions through $z_0 := (x_0,y_0)\in
 \mathbb{R}^2\subset\mathbb{C}^2$.

I hope someone can help me. Thank you.

A: If $x(z)$, $y(z)$ are the solutions of the complex ODE system
$$
\frac{dx(z)}{dz}=g(x(z),y(z))\\
\frac{dy(z)}{dz}=h(x(z),y(z))
$$
then you get as in the real case that along these characteristic curves
$$
\frac{d}{dz}f(x(z),y(z))=\frac{∂f}{∂x}(x(z),y(z))g(x,y)+\frac{∂f}{∂y}(x(z),y(z))h(x,y)=0,
$$
so that $f$ is constant along these curves.
With a parameter change for these characteristic curves you can also invert the relation of $x$ and $z$ so that $y$ is then a function of $x$.


text:
Q: Get multiple results as output for one condition on numpy array I am looking for a way to get multiple results for one condition of a numpy array.
Currently, I run the same where  condition twice on the same numpy array, to get two new arrays with different output.
import numpy as np
np_array = np.random.rand(3,3)
entry_array = np.where(np_array>=0.5,1,0)
mod_array = np.where(np_array>=0.5,np_array,0)

Does a possibility exists where I can fill the two new arrays entries, mod_array with only one loop over np_array.
Additionally, I am also looking for a solution for non-array output, like the following.
entries = np.where(np_array>=0,1,0).sum()
sum_entries = np.where(np_array>=0,np_array,0).sum()

I am especially interested in an efficient way, as my arrays have more than 100 million entries.

A: Few similar ideas:
def m1(np_array):
  entry_array = np.where(np_array>=0.5,1,0)
  mod_array = np.where(np_array>=0.5,np_array,0)
  return mod_array, entry_array

def m2(np_array):
  mod_array = np.where(np_array>=0.5,np_array,0)
  entry_array = np.array(mod_array, dtype=bool)+0
  return mod_array, entry_array

def m3(np_array):
  entry_array = np_array<0.5
  np_array[entry_array] = 0
  return np_array, 1-entry_array

Comparison: m1 seems slightly slower (up to 2x) than m2 and m3.
in_ = [np.random.rand(n,n) for n in [10,100,1000,10000,20000]]


text:
Q: why when I enter dart in cmd (windows) does it close immediately? Same with flutterfire recently, I accidentally deleted the entire file "path" (environment variable), perhaps it lacks some variable.
here's my flutter doctor:
[√] Flutter (Channel master, 3.8.0-14.0.pre.8, in Microsoft Windows [version 10.0.19044.2604],     localization ru-RU)
[√] Windows version (installed version of Windows - version 10 or higher)
[√] Android toolchain - development for Android devices (Android SDK version 32.1.0-rc1)
[√] Chrome - development for the Internet
[!] Visual Studio - development for Windows (Visual Studio Community 2022 17.4.3)
X Visual Studio lacks the necessary components. Please re-run the Visual Studio installer for the                   "Desktop Development using C++" workload and enable these components:
MSVC v142 - VS 2019 C++ x64/x86 Build Tools
- If multiple versions of the build tool are available, install the latest one
C++ CMake Tools for Windows
Windows 10 SDK
[√] Android Studio (version 2021.2)
[√] Android Studio (version 4.1)
[√] VS Code (version 1.75.1)
[√] Connected device (available 3)
[√] Network resources

it seems ok, but when I write to the console "dart..." or "flutterfire..." or just "dart" immediately closes
without error.
**[here is my system environment variable PATH](https://i.stack.imgur.com/kQixu.png)
[here is my user environment variable PATH](https://i.stack.imgur.com/RZvdH.png)
i am tried to reinstall flutter sdk, but it don't helps(

A: I solved this problem by adding this path to the system environment variables
C:\Program Files\Git\cmd


text:
Q: Hide page sections based on user role in Visual Composer I am trying to hide certain page sections based on user role in Visual Composer by adding Custom Content Shortcode in two text blocks. The first text block is at the top of the content I want to hide to all but admins and contains:
[is role=administrator]

The second text block, at the bottom of the content I want to hide, contains the closing tag,
[/is]

This is doing what it's supposed to and hiding the content, however, Visual Composer doesn't seem to like it, and VC shortcode winds up getting outputted to the page for admins, i.e. [/vc_column]. I can't get it to not display the VC shortcode. It's strange too that it only outputs the shortcode for admins.
If there is a different or better way to do what I'm trying to accomplish, I'm open to any solutions! I just want certain page sections to only be visible to admins.

A: You could use the header function to use Jquery to remove the elements via css class for each user.
Below is not a tested solution but can be a way to achieve what you wanted but not sure how to remove completely the output source code only hide it.
This can be added to the function file or built into a plugin.
        function insert_header()
        {
           // Check what user role
           global $current_user;
           $user_roles = $current_user->roles;
           $user_role = array_shift($user_roles);
           //return $user_role;
           // Check if the user has role
           if($user_role == "editor")
           {
             // inject jQuery or css to remove the elements by class
           }

        }

        add_action('wp_head','insert_header');


text:
Q: Id the device when submitting web forms So I'm trying to figure out a way the source code can extract an ID from the device that's submitting the form.
I'm trying to build a web app, that will be used by say, 10 people at most.
My goal is to prevent one person from entering everyone's data on web form.
Currently I'm using Php, to record entries into the Mysql Database.
Geo Location on web on the client to record address.


text:
Q: Mobile Number Validation for indian mobile am implementing an android application, i want to validate mobile number but nit succeed my code :
 final String regexStr = "^(?:(?:\\+|0{0,2})91(\\s*[\\-]\\s*)?|[0]?)?[789]\\d{9}$";
final EditText chmobno = (EditText)login.findViewById(R.id.chmobno);
 mb=chmobno.getText().toString();

on button click
btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if( mb.matches(regexStr)){

                Toast.makeText(MainActivity.this,
                        "Login Sucessfull", Toast.LENGTH_LONG).show();
                login.cancel();
                Intent i=new Intent(MainActivity.this,TSO_Home.class);
                startActivity(i);
            }
            else{
                    Toast.makeText(MainActivity.this,
                            "Please enter Valid Mobile Number", Toast.LENGTH_LONG).show();
            }

when i enter valid number it goes else part.. please help me to find the error

A: final String regexStr = "^(?:(?:\\+|0{0,2})91(\\s*[\\-]\\s*)?|[0]?)?[789]\\d{9}$";
final EditText chmobno = (EditText)login.findViewById(R.id.chmobno);
 mb=chmobno.getText().toString();
btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if( mb.matches(regexStr)){

                Toast.makeText(MainActivity.this,
                        "Login Sucessfull", Toast.LENGTH_LONG).show();
                login.cancel();
                Intent i=new Intent(MainActivity.this,TSO_Home.class);
                startActivity(i);
            }
            else{
                    Toast.makeText(MainActivity.this,
                            "Please enter Valid Mobile Number", Toast.LENGTH_LONG).show();
            }


text:
Q: How to make the up-button go back to a parent activity on the back stack? I'd like to implement the following behavior for the up-button:

*

*If an instance of the parent activity is on the back stack, return to the top-most instance of that parent activity.

*If there is no instance of the parent activity on the back stack, create a new instance.

Actually, when I first read about the difference between up and back, this behaviors was what I expected as default. However, I have seen now, that NavUtils.navigateUpFromSameTask(this); always creates a new instance of the parent activity, ignoring the fact, that there is one readily available on the back stack.
Thanks for any advice.

A: Try to specify launch mode for your activity in Manifest  android:launchMode="singleInstance" or android:launchMode="singleTop" ,look at this question for more info Android launchmode="singleTask" does not work as expected

A:
If an instance of the parent activity is on the back stack, return to the top-most instance of that parent activity.

If this is meant to clear the back stack down to this top-most instance, I recently solved this issue customizing the up-navigation using the activity's onOptionsItemSelected() and adding the FLAG_ACTIVITY_CLEAR_TOP-flag (link) to the Intent - while only switching the launch mode did not end up in the back stack I was expecting:
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
    Intent parentActivityIntent = NavUtils.getParentActivityIntent(this);
    parentActivityIntent.setFlags(FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(parentActivityIntent);
}

Also have a look at http://developer.android.com/training/implementing-navigation/ancestral.html#NavigateUp.


text:
Q: Эффект размытия внутри диалогового окна Android Всем привет, кто-нибудь знает, как реализовать такой динамический фон у диалогового окна?
Пример

A: getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
c API версии 14 не работает
с другой стороны - если надо размыть свою собственную activity - то способ есть. Заблюрить с 4.0 только чужое нельзя


text:
Q: String to dictionary (Get values from QRCode String) I am trying to generate QRCode and then read it in. My problem is that I do not know how to get values from the QRCode string.
String inside my QRCode is following: ["firstName": "John", "lastName": "Bush"]
I achieved it like this:
let dict = ["firstName":firstName, "lastName": lastName]
dict.description

Now I want to get the values out of it, how should I do this? I tried to convert the string back to dictionary but couldn't do it.

A: If you're really interested in parsing this result, there is of course ways to do it. It's never going to be consistently successful unless there is a consistent format coming from your source. In the event that it is consistent, you could of course do something like this:
//get the string representation of our dictionary
let code = "[\"firstName\": \"firstName\", \"lastName\": \"lastName\"]"
//remove the brackets
let bracketless = String(code.characters.dropFirst().dropLast())
//get rid of our quotes
let quoteless = bracketless.replacingOccurrences(of: "\"", with: "")
//split our dictionary by key/value pairs
let pairs = quoteless.components(separatedBy: ", ")
//now split our key/value pairs into each key and value component respectively
let values: [[String]] = pairs.map { $0.components(separatedBy: ": ") }

//create ourself a dictionary to populate with our parsed data
var dict: [String:Any] = [:]
values.forEach { dict[$0[0]] = $0[1] } //populate the dictionary
print(dict) // ["lastName": "lastName", "firstName": "firstName"]

It's always better to use a standardized format (e.g. JSON). Perhaps in your situation this just isn't an option. I would still wonder why then you're in said situation..

A: This is rather tricky, the result from description is not really meant to be used as an exchange format. The best thing to do would be to use a different format to generate your QR Codes. But let's assume that it's too late for this.
To get the data back you need to write a parser, since the system doesn't provide one for the description format. Sounds hard, but it really is not. You might consider using the String method components(separatedBy:), but this will turn out very inefficient. The Foundation Scanner class is a much better tool for this.
The simplest parser to write is a "recursive descent" parser. This means for each part you want to recognise you write a function that calls such functions for sub-parts. So lets see what we have here:

*

*The outer layer is the dictionary. This starts with the string "[", then we have key/value pairs separated by "," and finally another "]". (There also might be the case of an empty dictionary which is just "[]"

*Then we have a pair. This is a string inside quotes, followed by a ":" and another quoted string.

*The last part is the quoted string. There we have the quote ", and any other characters up to the next quote.

So in pseudo-code this will look something like this:
func dictionary() {
   expect("[")
   if !read("]") {
      repeat {
          pair()
      } while read(",")
   }
   expect("]")
}

func pair() {
    quotedString()
    expect(":")
    quotedString()
}

func quotedString() {
   expect("\"")
   readUpTo("\"")
   expect("\"")
}

Here expect, read and readUpTo are placeholders for the methods provided by the Scanner class. If we provide those this basically is the complete parser. But like this it is not very useful as it just ignores the data. So we need to extend our parser so it actually returns the found data.
The final result then could look something like this:
let scanner = Scanner(string: string)

func dictionary() -> [String: String]? {
    guard scanner.scanString("[", into: nil) else { return nil }

    var result: [String: String] = [:]

    if !scanner.scanString("]", into: nil) {
        repeat {
            guard let (key, value) = pair() else { return nil }
            result[key] = value
        } while scanner.scanString(",", into: nil)
    }

    guard scanner.scanString("]", into: nil) else { return nil }

    return result
}

func pair() -> (String, String)? {
    guard let key = quotedString(),
        scanner.scanString(":", into: nil),
        let value = quotedString()
    else {
            return nil
    }

    return (key, value)
}

func quotedString() -> String? {
    guard scanner.scanString("\"", into: nil) else { return nil }

    var result: NSString? = nil
    guard scanner.scanUpTo("\"", into: &result), let string = result as? String else { return nil }

    guard scanner.scanString("\"", into: nil) else { return nil }

    return string
}

A little bit more code that the hacky solution using string splitting, but not really complicated either and much more flexible. Here we won't have any problems if the strings themselves contain "," or ":". The performance will be better too, since here we look at every character only once. The other solution will have to look at each character three times.
It still has one problem though: If any of your strings contain the double quote character this parser will fail. The description property of the dictionary will output this in a backslash-quoted form as \" - this will have to be handled in quotedString.


text:
Q: Длинное сложение Даны числа N, M, A, B, где N - длина числа A, M - длина числа B.
Требуется найти и вывести сумму чисел A и B.
Входные значения
Со стандартного устройства ввода в первой строке вводятся числа N (1 <= N <= 1000) - длина числа A и M (1 <= M <= 1000) — длина числа B.
Во второй строке вводится число A(1 <= A).
В третьей строке вводится число B(1 <= B).
Выходные значения
Требуется найти и вывести сумму чисел A и B. Выводить пробел в конце строки не нужно.
Пример входных данных
17 17
56356356456456456
87987987897897980
Пример выходных данных
144344344354354430

A: Учитывая небольшую длину (до 1000 цифр), я решил написать программу, которая складывает по-циферно (как в школьном алгоритме), в реальных библиотеках длинной арифметики складывают не по-циферно, а машинными словами (по 32 или 64 бита), для эффективности и скорости.
Благодаря по-циферному сложению не нужно даже переводить в двоичную форму числа, прямо символы и складываем.
Попробовать онлайн!
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>

#define MIN(X, Y) (((X) <= (Y)) ? (X) : (Y))
#define MAX(X, Y) (((X) >= (Y)) ? (X) : (Y))

int main() {
    int N = 0, M = 0;
    if (scanf("%d %d\n", &N, &M) != 2 || N < 1 || N > 1000 || M < 1 || M > 1000) {
        printf("Bad N, M!\n");
        return -1;
    }
    char A[1024], B[1024], C[1024];
    memset(C, 0, sizeof(C));
    int K = sizeof(C) - 1;
    fgets(A, N + 2, stdin);
    fgets(B, M + 2, stdin);
    if (strlen(A) != N + 1 || strlen(B) != M + 1) {
        printf("Bad nums lengths %d and %d!\n", ((int)strlen(A)) - 1, ((int)strlen(B)) - 1);
        return -1;
    }
    A[N] = 0;
    B[M] = 0;
    int carry = 0;
    for (int i = 1, hi = MAX(N, M) + 1; i <= hi; ++i) {
        int sum = (i <= N ? A[N - i] - '0' : 0) + (i <= M ? B[M - i] - '0' : 0) + carry;
        if (sum >= 10)  {
            carry = 1;
            sum -= 10;
        } else
            carry = 0;
        C[K - i] = (char)(sum + '0');
    }
    char const * pC = C;
    while (!*pC)
        ++pC;
    while (*(pC + 1) && *pC == '0')
        ++pC;
    printf("%s\n", pC);
    return 0;
}

Ввод:
17 17
56356356456456456
87987987897897980

Вывод:
144344344354354436


text:
Q: Opening Certain Sites in Ubuntu 14.04 I Searched a lot about this Question and no answer could help me :(
My problem is in connect to certain sites in Ubuntu 14.04 (Specially SSL connections mostly with Error 100 (Connection was reset))! Java Scripts Also not working properly! I update my fire fox But it not works!
I have a windows 7 along side my Ubuntu, But in it All website connects without any problem!
for example Online Banks not opens in ubuntu But opens in Windows!
Can Anybody help me with this issue? It makes me mad!
Thanks!

A: Error 100 :-
100 Continue
This means that the server has received the request headers, and that the client should proceed to send the request body (in the case of a request for which a body needs to be sent; for example, a POST request). If the request body is large, sending it to a server when a request has already been rejected based upon inappropriate headers is inefficient. To have a server check if the request could be accepted based on the request's headers alone, a client must send Expect: 100-continue as a header in its initial request and check if a 100 Continue status code is received in response before continuing (or receive 417 Expectation Failed and not continue).
run firefox in safe mode and check again!!


text:
Q: how to calculate the turnover in powerbi I want to create a report in power Bi that shows the turnover for each year but in my database a turnover can not be equal to the total amount of the bills because there can be assets to be deducted. so in my database there is  operation_code table which contains a SENS column this column indicates if this operation is either input or output and the turnover will be calculated as follows: if (CODE_OP.SENS = output), + sum (ENT.HTMT / ENT .DEVP) else if (CODE_OP.SENS = input), - sum (ENT.HTMT / ENT.DEVP)
i did a test with SQL Statements :
SELECT YEAR(ENT.PIDT) ,T020.SENS,
CASE
     WHEN T020.SENS= 2 THEN
      sum (ENT.HTMT / ENT.DEVP)
      WHEN T020.SENS = 1 THEN -1 * sum (ENT.HTMT / ENT.DEVP)
    END as CA FROM ENT
left join T020  on
    T020.OP = ENT.OP
WHERE ENT.PICOD=4 AND ENT.TICOD='C'  AND ENT.DOS=998
GROUP BY YEAR(ENT.PIDT)--,T020.SENS

but when i try to do it in power BI Using DAX by creating a measure
Measure =

Switch ( True();

 ALL(T020[SENS])=2,0;SUM(ENT[HTMT])/SUM(ENT[DEVP]) ;

 ALL(T020[SENS])=1,0; SUM(ENT[HTMT])/(SUM(ENT[DEVP]))
 )

an error appear when i try to use the measure that it is impossible to display the visual element  . enter image description here

A: The following DAX should do the trick:
Measure =
CALCULATE(
    SUMX(ENT, DIVIDE(ENT[HTMT], ENT[DEVP])),
    T020[SENS] = 2
)
- CALCULATE(
    SUMX(ENT, DIVIDE(ENT[HTMT], ENT[DEVP])),
    T020[SENS] = 1
)


text:
Q: Simplify SQL Query using variable I want to simplfy my T-SQL query. It is like this :
SELECT

    t.a AS [Column A],
    t.b AS [Column B],
    t.c AS [Column C],
    (t.a - t.b - t.c) AS [Column D],
    CASE
      WHEN (t.a - t.b - t.c) = 0 THEN 'Equals'
      WHEN (t.a - t.b - t.c) > 0 THEN 'Greater'
      WHEN (t.a - t.b - t.c) < 0 THEN 'Less'
    END AS [Status]

FROM
    Table1 AS t;

It would be nice to put (t.a - t.b - t.c) into a variable, so I can reuse it on all places it occurs, because the expression may change over time.
I could not figure out how to do this without changing the existing query significantly.

A: Use Cross Apply
SELECT
    t.a AS [Column A],
    t.b AS [Column B],
    t.c AS [Column C],
    [Column D],
    CASE
      WHEN [Column D] = 0 THEN 'Equals'
      WHEN [Column D] > 0 THEN 'Greater'
      WHEN [Column D] < 0 THEN 'Less'
    END AS [Status]

FROM
    Table1 AS t
    CROSS APPLY (SELECT t.a - t.b - t.c AS [Column D]) AS t2

A: You can use a CTE (Common Table Expression) like this:
;WITH CTE AS
(
    SELECT
        t.a AS [Column A],
        t.b AS [Column B],
        t.c AS [Column C],
        (t.a - t.b - t-c) AS [Column D]
    FROM
        Table1 AS t
)
SELECT
    [Column A],
    [Column B],
    [Column C],
    [Column D],
    CASE
      WHEN [Column D] = 0 THEN 'Equals'
      WHEN [Column D] > 0 THEN 'Greater'
      WHEN [Column D] < 0 THEN 'Less'
    END AS [Status]
FROM
    CTE

This defines a CTE - something like a "ad-hoc" view - that you can use to handle things like calculations, aggregations etc. and then select from it (or use other SQL statements against it). The CTE only exists for the one, next statement - it doesn't get "persisted" for multiple SQL statements. But it's quite handy to handle situations like this

A: I don't know what's your question. But here is some information for you.
If you use SQL Server, you can assign the returns of your query to a variable like that:
SELECT @var = value
FROM yourTable

But beware, if you have multiple rows in the result, only the last row will be taken to your variables.
If you just want to save power with your (t.a - t.b - t.c) statement, it won't be necessary as SQL Server will evaluate those expression just one time and make the data compare for each WHEN until one matches.


text:
Q: Creating a folder inside Mac OS App I want a an app that is "self-contained" (I don't know if i use the right word. "putting the app into trash bin will remove everything" is what I meant). But the app requires some resources to run. I usually put those resources into a folder. I want to move those resources into the App folder ( package contents). Can I do that? Is it a good practice to do that?
When I test the app directly running from Xcode, the App runs fine. But if i run it from finder, the app will say fails to create resources folder because permission denied. I checked the app's folder permission - User(me) has read/write access. I am wondering what is causing this different behavior.
The last option is to use Application Support folder, but I don't want to leave trails when user deletes the app.
Can someone help me out here?

A: Applications live in the directory /Applications, where users don't generally have write access. Requiring an app to have write permission in system folders is extremely bad practice.
Runtime files should live in ~/Library/Application Support. While that folder tends to accumulate some cruft, unless your application leaves behind really large files, that shouldn't be a problem.
If you want your application to be self-contained, it needs to come with all the files it needs from the get-go, and not write anything to disk.


text:
Q: Are Python prepared statements vulnerable to SQL injection I'm starting to program a Python application that works with databases. Reading about prepared statements, I found how I'm supposed to write them:
...
strSQL = "select * from myTable where aField = $s" % (aValue)
cursor.execute(strSQL)
...

My question is: Isn't this vulnerable to SQL injection? If so, how can I prevent it?
Thank you

A: You are using the string formatting operator instead of bound SQL parameters, so your code is indeed at risk of SQL injection (once you fix the $s, which I take to be a typo).
The correct form is:
strSQL = "select * from myTable where aField = %s"
cursor.execute(strSQL, [aValue])

A: The way you have it, absolutely! Here's how you would "help" get around the sql injection
strSQL = "select * from myTable where aField = %s"
cursor.execute(strSQL, [aValue])

Pass the values as a list/tuple to the second argument on the cursor execute


text:
Q: No module named 'xlwt' even though I have it through Anaconda I've been trying to run import xlwt from a Python program and the prompter has told me that no such module exists. However I know that I have it through Anaconda. I also ran conda update xlwt in the prompt to know if it was the latest version, which it was (I have updated Anaconda as well). I'm using Python 3.4.
What I've tried is to include
    import sys
    sys.path.append('C:\Users\Guda\Anaconda\Lib\site-packages')
which got me the error
sys.path.append('C:\Users\Guda\Anaconda\Lib\site-packages')
               ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3:   truncated \UXXXXXXXX escape

I've also tried to copy the xlwt folder from C:....\Anaconda\Lib\site-packages to C:\Users...\Python34\Lib\site-packages and simply using import xlwt (removing the import sys and the sys.path.append command).
It gave me the error
 File "dataomv.py", line 5, in <module>
 import xlwt
 File "c:\Python34\lib\site-packages\xlwt\__init__.py", line 3, in <module>
 from Workbook import Workbook
 ImportError: No module named 'Workbook'

From what I've googled I've seen that I must check whether init.py exists, which is does in the site-packages in both the Anaconda\Lib... and in Python34... folders.
Can anybody shed some light into this matter?
Thanks in advance!

A: Try module xlwt-future, it is written for python 3.x through  future compatibility (of python 2 and 3) module.


text:
Q: How access values from different classes without using parameters in java? For example, my program is like that,
one java file,this is my fixed class.
class Dynamic{
 String s;
  public void program(){
   System.out.println(s);
   }
}

here another java file,this is class dynamic,
class Source{
 public static void main(String[] args)
 {
 String s = "Hello world";
 Dynamic d=new Dynamic();
 d.program();
 }}

I want to print s in dynamic class. And I don't want to use s as a parameter and also If I changes my sources class, it will works. Is any other method is there?

A: You may make String s of dynamic class public static -
public static String s;

Then you can get it from any where like this -
dynamic.s

But in OOP worlds making variable public is not recommended.
You can also make a public getter method like this (the best way) in your dynamic class-
public String getS(){
 return this.s;
}

A: You can do this using "global variables". But i don't know if is this what you are looking for.
class Source{
  public static String s = "Hello world";
  public static void Main(String args[]) {
    dynamic d=new dynamic;
    d.program();
  }
}

class Dynamic{
  public void program(){
    System.out.println(Source.s);
  }
}

Anyway, as a style rule, classes's names should be in CamelCase.


text:
Q: PHP Utf8 MySQL_Querying, JSON_Encoding I have a MySQL DB, encoded in UTF8, where some records have 'ā's in them (in case it doesn't show up right in SO, that's an 'a' with a line above it).
There is a PHP script that is getting the records, putting them in an array, and json_encoding them. No matter whether the script is being invoked by ajax or the webpage, the 'ā's show up as question marks. Where is the problem, and how do I fix it?
Thanks,
Jamie McClymont
EDIT: Forgot to mention that the 'ā's show up fine in PHPMyAdmin

A: For the text to print correctly you need to set the charset of the mysql connection and the page
For the connection the following query will work
set names utf8

Run this query right after connecting
If the charset is still incorrect try adding
header('Content-Type: application/json; charset=utf-8');

assuming you're outputting json
http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html