text:
Q: Error when connecting to database using unixODBC on IBM AIX I am facing an error while connecting to database using unixODBC on IBM AIX 64bit
DB2 client V9.7 is installed on the machine.
Found on net that it can be due to library file:' libdb2o.so ' missing and in that case update to DB2 V9.7 Fix Pack3.
Updated DB2 client to DB2 V9.7 Fix Pack 4 but still no success.
On trying to connect to database using: isql -v  it gives following error:
[01000][unixODBC][Driver Manager]Can't open lib '/opt/IBM/db2/V9.7_01/lib64/db2o.o' : file not found
[ISQL]ERROR: Could not SQLConnect
Details of .odbc.ini :
[db2_odbc_source]
Description     = IBM DB2 ODBC data source
Driver          = db2_odbc_driver
Trace           = Yes
DMEnvAttr       = SQL_ATTR_UNIXODBC_ENVATTR={DB2_CLI_DRIVER_INSTALL_PATH=/home/UserName}

Details of .odbcinst.ini :
[db2_odbc_driver]
Description = IBM DB2 ODBC driver
Driver      = /opt/IBM/db2/V9.7_01/lib64/db2o.o
FileUsage   = 1
DontDlClose = 1

Environment variables DBINSTANCE and ODBCINI are set.
Your help will be greatly appreciated.
Thanks.

A: libdb2o.o is used for connectivity via unixodbc for db2 database on 64 bit OS except nt64.on nt64,we use probably db2clio.o


text:
Q: Counting percent of rows with category out of total number of rows using Dynamic Linq How to achieve this using Dynamic Linq Join and Dynamic Linq SelectMany

A: Desired result is in q and q2.
q shows combination of aggregates from different levels of grouping in one expression.
q2 uses calculated agg from prev levels and generates shorter SQL query.
var grp=(db.A as IQueryable).GroupBy("grp","it");
var grp2=grp.Select("new(key as key,new(count() as cnt) as agg)");
foreach(dynamic r in grp2) Console.WriteLine("grp:"+r.key+"\tcnt:"+r.agg.cnt);
//foreach(dynamic r in grp) Console.WriteLine(r.Key+"\t"+r.Count()); // throws RuntimeBinderException
Console.WriteLine("----------------------");
var cat=(db.A as IQueryable)
    .SelectMany("B","new(outer as a,inner as b)")
    .GroupBy("new(a.grp,b.cat)","it");
var cat2=cat.Select("new(key as key,new(count() as cnt) as agg)");
foreach(dynamic r in cat2) Console.WriteLine("grp:"+r.key.grp+"\tcat:"+r.key.cat+"\tcnt:"+r.agg.cnt);

Console.WriteLine("----------- result -----------");
var q=cat.Join("c",grp,"g","c.key.grp","g.key","new(g.key as grp,c.key.cat,new(c.count()*100/g.count() as percent) as agg)");
foreach(dynamic r in q) Console.WriteLine("grp:"+r.grp+"\tcat:"+r.cat+"\tpercent:"+r.agg.percent);
Console.WriteLine("----------- result2 -----------");
var q2=cat2.Join("c",grp2,"g","c.key.grp","g.key","new(g.key as grp,c.key.cat,new(c.agg.cnt*100/g.agg.cnt as percent) as agg)");
foreach(dynamic r in q2) Console.WriteLine("grp:"+r.grp+"\tcat:"+r.cat+"\tpercent:"+r.agg.percent);

q produces the following SQL query:
SELECT
1 AS [C1],
[Project4].[grp] AS [grp],
[Project4].[cat] AS [cat],
([Project4].[C1] * 100) / [Project4].[C2] AS [C2]
FROM ( SELECT
    [Project3].[cat] AS [cat],
    [Project3].[grp] AS [grp],
    [Project3].[C1] AS [C1],
    (SELECT
        COUNT(1) AS [A1]
        FROM [dbo].[A] AS [Extent6]
        WHERE ([Project3].[grp] = [Extent6].[grp]) OR (([Project3].[grp] IS NULL) AND ([Extent6].[grp] IS NULL))) AS [C2]
    FROM ( SELECT
        [Distinct1].[cat] AS [cat],
        [Distinct2].[grp] AS [grp],
        (SELECT
            COUNT(1) AS [A1]
            FROM  [dbo].[A] AS [Extent4]
            INNER JOIN (SELECT
      [B].[aid] AS [aid],
      [B].[cat] AS [cat]
      FROM [dbo].[B] AS [B]) AS [Extent5] ON [Extent4].[id] = [Extent5].[aid]
            WHERE (([Distinct1].[grp] = [Extent4].[grp]) OR (([Distinct1].[grp] IS NULL) AND ([Extent4].[grp] IS NULL))) AND ([Distinct1].[cat] = [Extent5].[cat])) AS [C1]
        FROM   (SELECT DISTINCT
            [Extent1].[grp] AS [grp],
            [Extent2].[cat] AS [cat]
            FROM  [dbo].[A] AS [Extent1]
            INNER JOIN (SELECT
      [B].[aid] AS [aid],
      [B].[cat] AS [cat]
      FROM [dbo].[B] AS [B]) AS [Extent2] ON [Extent1].[id] = [Extent2].[aid] ) AS [Distinct1]
        INNER JOIN  (SELECT DISTINCT
            [Extent3].[grp] AS [grp]
            FROM [dbo].[A] AS [Extent3] ) AS [Distinct2] ON ([Distinct1].[grp] = [Distinct2].[grp]) OR (([Distinct1].[grp] IS NULL) AND ([Distinct2].[grp] IS NULL))
    )  AS [Project3]
)  AS [Project4]

q2 produces shorter SQL query:
SELECT
1 AS [C1],
[GroupBy2].[K1] AS [grp],
[GroupBy1].[K2] AS [cat],
([GroupBy1].[A1] * 100) / [GroupBy2].[A1] AS [C2]
FROM   (SELECT
    [Extent1].[grp] AS [K1],
    [Extent2].[cat] AS [K2],
    COUNT(1) AS [A1]
    FROM  [dbo].[A] AS [Extent1]
    INNER JOIN (SELECT
      [B].[aid] AS [aid],
      [B].[cat] AS [cat]
      FROM [dbo].[B] AS [B]) AS [Extent2] ON [Extent1].[id] = [Extent2].[aid]
    GROUP BY [Extent1].[grp], [Extent2].[cat] ) AS [GroupBy1]
INNER JOIN  (SELECT
    [Extent3].[grp] AS [K1],
    COUNT(1) AS [A1]
    FROM [dbo].[A] AS [Extent3]
    GROUP BY [Extent3].[grp] ) AS [GroupBy2] ON ([GroupBy1].[K1] = [GroupBy2].[K1]) OR (([GroupBy1].[K1] IS NULL) AND ([GroupBy2].[K1] IS NULL))

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I stop my robot after it drives forward over a black band and say number 4 out loud? %%sim_magic_preloaded --background Coloured_bands -R
# Program to count the bands aloud

# Start the robot moving
tank_drive.on(SpeedPercent(15), SpeedPercent(15))

# Initial count value
count = 0

# Initial sensor reading
previous_value = colorLeft.reflected_light_intensity_pc

# Create a loop
while True:

    # Check current sensor reading
    current_value = colorLeft.reflected_light_intensity_pc

    # Test when the robot has entered a band
    if previous_value==100 and current_value < 100:
        # When on a new band:
        # - increase the count
        count = count + 1
        # - display the count in the output window
        print(count)
        # - say the count aloud
        say(str(count))

    # Update previous sensor reading
    previous_value = current_value

Need some help with this coding,im trying to make to make the robot stop after it goes over the black band which is the forth band and also it doesnt say out loud number 4 once it goes over the black band

A: import time

previous_value = colorLeft.color

tank_drive.on(SpeedPercent(15), SpeedPercent(15))

count = 1

while True:
    current_value = colorLeft.color
    print(current_value)

    if previous_value==6 and current_value != 6:
        print(count)
        say(str(count))

        count += 1

    #Now it should stop at band 4
    if count > 4 and current_value==6:
        time.sleep(1)
        tank_drive.off()
        break

    previous_value = current_value


text:
Q: Async code implementation correctness I have an application where I make a call like this:
myViewModel.ProcessDirectoryAsync(rootDirectoryInfo);

and in myViewModel:
public async ProcessDirectoryAsync(DirectoryInfo rootDirectoryInfo)
{
    await Task.Run(() => ProcessDirectory(rootDirectoryInfo));
}

public void ProcessDirectory(DirectoryInfo rootDirectoryInfo)
{
    // do work and update progress in UI with a bunch of data
}

The idea is that I want my ui to show multiple threads of work, each updating the UI with its progress and data independently.
This code works just fine.
But I wonder if it is not right.  If I put an await (as recommended by resharper :) ) on this line:
await myViewModel.ProcessDirectoryAsync(rootDirectoryInfo);

Then I see the threads progress serially, rather than in parallel.  Which is not what I want.
So first, is there something inherently evil in the way I've implemented this (which works), and if so what is the correct way?

A: the indirection and async/await seem unneccessary. just call
Task.Run(() => myViewModel.ProcessDirectory(rootDirectoryInfo));
btw., you should always await an async, and async functions should return a Task, except in event handlers. but all of this unneccessary here.


text:
Q: jQuery tabs - need 'All' tab with whole form and individual tabs for each form section I've tried to google my requirement but without luck. What I have is a form that is broken into several tabs, all which works perfectly. However, now I've been asked to provide an 'All' tab with the whole form, in addition to the individual tabs for each section.
Seems like a fairly straightforward request, but I can't see how I can implement it using the jQuery tabs functionality?

A: I'm relatively new to jQuery so there might be a much better approach.  But if I had to implement this myself I would look into reparenting the contents of the "tab divs" in the select event of the tab.

A: I think Ken is on the right trail, but I might just clone the appropriate DOM elements. If there are forms, you're going to probably want a single submit instead of multiple so reparenting isn't ideal.
Cloning them will also keep the height and sizing more consistent if your tabs expand based on the contents.
Maybe look at the following:
http://www.evotech.net/blog/2008/11/jquery-tutorial-dom-manipulation-and-sorting/
On the other hand, re-parenting avoids any synchronization issues you might have between each screen.

A: Rather than having actual tabs, it might be easier for your 'tab' buttons to just hide all form elements that are not part of that 'tab'.


text:
Q: Difficulty in specifying mesh refinement I am trying to give a region within a 3D volume a finer mesh than the rest of the volume. My problem is more complicated but here is a minimum working example.
I define a 3D cuboid and try and have a fine mesh in a region between an inner and outer hemisphere.
Needs["NDSolve`FEM`"];
Len = 150/1000;  (*length of plate  *)
ht = 15/1000; (* height *)
wd = 80/1000; (* width *)
reg = BoundaryDiscretizeRegion[
  Cuboid[{-Len/2, -wd/2, 0}, {Len/2, wd/2, ht}]]

   rcp = 0.02;
mrf = Compile[{{c, _Real, 2}, {a, _Real, 0}},
   Block[{d, com},
    com = Total[c]/3;
    d = Norm[com];
    If[0.8 rcp < d < 1.2 rcp && a > 10^-10, True, False]
    ]
   ];
mesh = ToElementMesh[reg, MeshRefinementFunction -> mrf];
Show[mesh["Wireframe"],
 PlotRange -> {{-Len/2, Len/2}, {-wd/2, wd/2}, {0, ht/4}}]

This clearly shows an annulus on the boundary but it is not the correct size. If I extract the boundary points and plot them together with the circles defining the region of refinement we see that the annulus is too small.
cc = mesh["Coordinates"];
c1 = Select[cc, #[[3]] == 0 &];
ListPlot[c1[[All, {1, 2}]],
 PlotRange -> {{-0.03, 0.03}, {-0.03, 0.03}},
 AspectRatio -> Automatic,
 Epilog -> {Circle[{0, 0}, 0.8 rcp], Circle[{0, 0}, 1.2 rcp],
   Red, PointSize[0.02], Point[{0, 0}]}]

Have I done something silly? What is wrong? I know I am taking my reference from the centroid of each element and this will make a slight difference but if I increase the "MaxCellMeasure" it does not change the position.
Edit
Due to Henrik Schumacher and user21, who have very sharp eyes, they show an elementary mistake. I averaged the 4 points defining the element by dividing by 3. I probably picked this up by copying the MeshRefinementFunction from a 2D problem. Here is the corrected version. I use Mean as a variant on the two other methods given in their answer.
rcp = 0.02;
mrf = Compile[{{c, _Real, 2}, {a, _Real, 0}},
   Block[{d, com},
    com = Mean[c];
    d = Norm[com];
    If[0.8 rcp < d < 1.2 rcp && a > 10^-10, True, False]
    ]
   ];
mesh = ToElementMesh[reg, MeshRefinementFunction -> mrf];
Show[mesh["Wireframe"],
 PlotRange -> {{-Len/2, Len/2}, {-wd/2, wd/2}, {0, ht/4}}]

cc = mesh["Coordinates"];
c1 = Select[cc, #[[3]] == 0 &];
ListPlot[c1[[All, {1, 2}]],
 PlotRange -> {{-0.03, 0.03}, {-0.03, 0.03}},
 AspectRatio -> Automatic,
 Epilog -> {Circle[{0, 0}, 0.8 rcp], Circle[{0, 0}, 1.2 rcp],
   Red, PointSize[0.02], Point[{0, 0}]}]

All working properly now.

A: We want to generate a tet mesh, so
com = Total[c]/4;

or better
com = Total[c]/Length[c];

would be more appropriate.


text:
Q: "The exam date" vs. "the exam day"

*

*I will send you my proposal two months before the exam date.

*I will send you my proposal two months before the exam day.

Which one is more correct?

A: As Jim said, both variations are acceptable, and they are functionally interchangeable.
Stylistically, I prefer date over day in the relatively formal context of your example sentence. Here's what sounds most natural to my ears:

I will send you my proposal two months prior to the exam date.

Again, both of your original examples are grammatically correct. I'm just musing on nuances of style here.
Something else to consider: in your example, "exam date" and "exam day" are basically interchangeable as the objects of a preposition. They barely differ. However, it's less simple when we cast them as the SUBJECT of a clause/sentence. "Exam day" is acceptable (similar to game day, Christmas day, graduation day, even Monday & today) and is interchangeable with "the day of the exam".
On the other hand, "exam date" does not work as a sentence subject; instead, you could say "the date of the exam", but note the difference in meaning ("date" = the calendar number, "day" = the occasion/event).


text:
Q: Android Retrofit Post Data I am working with an Android Recyclerview with Retrofit, it is working without any Post Data. I need to post some data in my current Code.
Below is my Current ApiInterface
public interface ApiInterface {
   @GET("mypage.php")
   Call<Pojo> getData();
}

And in my activity I am calling this by below code
ApiInterface apiInterface = (ApiInterface) RetrofitClient.getRetrofitInstance().create(ApiInterface.class);
    Call<Pojo> listingdata = apiInterface.getData();
    listingdata.enqueue(new Callback<Pojo>() {
        @Override
        public void onResponse(Call<Pojo> call, Response<Pojo> response) {

            if(response.isSuccessful()){
                recycleradpter recycleradpter = new recycleradpter(response.body().getData());
                recyclerView.setAdapter(recycleradpter);
                progressbar2.setVisibility(View.GONE);
            }

        }

        @Override
        public void onFailure(Call<Pojo> call, Throwable t) {
            //System.out.println("12345678934567890234567890");
            //Toast.makeText(getActivity(), "No Connected internet", Toast.LENGTH_SHORT).show();
           progressbar2.setVisibility(View.GONE);
            dialogfunction();
        }
    });

How Can I get data based on passed data in above code

A: If you want to send a post request then you have to create a method like below. The calling of the method will be similar to that of get request. Just pass the parameters of your post body. You can for details here.
 @POST("mypage.php")
 Call<Pojo> postData(
     @Field("param1") String param1,
     @Field("param2") int param2
 );

A: @FormUrlEncoded
@POST("your_php_file.php")
Call<ResponseBody> getLanguageCall(@Field("lang_code") String lang_code, @Field("app_id") String app_id);

private void getLanguageCall() {
    progressDialog.setVisibility(VISIBLE);
    Call<ResponseBody> call = ApiClient.getClient().create(ApiInterface.class).getLanguageCall(PreferenceManager.getStringPreference(SplashActivity.this, appLanguage), PreferenceManager.getStringPreference(SplashActivity.this, PreferenceManager.APP_ID));
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            progressDialog.setVisibility(View.GONE);
            if (!response.isSuccessful()) {
                showToast(response.code() + " : " + response.message());
                return;
            }
            try {
                JSONObject root = new JSONObject(response.body().string());
                HashMap<String, String> list = new HashMap<String, String>();
                JSONArray keyData = root.getJSONArray("key_data");
                for (int i = 0; i < keyData.length(); i++) {
                    JSONObject obj = keyData.getJSONObject(i);
                    list.put(obj.getString("Key_Name").toLowerCase(), obj.getString("Key_Value"));
                }
                finish();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            t.printStackTrace();
            progressDialog.setVisibility(View.GONE);
            showToast("Error ! Server Error.");
        }
    });
}


text:
Q: How can I forward fill a dataframe column where the limit of rows filled is based on the value of a cell in another column? So I am trying to forward fill a column with the limit being the value in another column. This is the code I run and I get this error message.
import pandas as pd
import numpy as np

df = pd.DataFrame()

df['NM'] = [0, 0, 1, np.nan, np.nan, np.nan, 0]

df['length'] = [0, 0, 2, 0, 0, 0, 0]

print(df)

   NM      length
0  0.0       0
1  0.0       0
2  1.0       2
3  NaN       0
4  NaN       0
5  NaN       0
6  0.0       0

df['NM'] = df['NM'].fillna(method='ffill', limit=df['length'])

print(df)

ValueError: Limit must be an integer
The dataframe I want looks like this:
       NM      length
    0  0.0       0
    1  0.0       0
    2  1.0       2
    3  1.0       0
    4  1.0       0
    5  NaN       0
    6  0.0       0

Thanks in advance for any help you can provide!

A: I do not think you want to use ffill for this instance.
Rather I would recommend filtering to where length is greater than 0, then iterating through those rows to enter the NM value from that row in the next n+length rows.
for row in df.loc[df.length.gt(0)].reset_index().to_dict(orient='records'):
    df.loc[row['index']+1:row['index']+row['length'], 'NM'] = row['NM']

To better break this down:

*

*Get rows containing change information be sure to include the index.
df.loc[df.length.gt(0)].reset_index().to_dict(orient='records')

*iterate through them... I prefer to_dict for performance reasons on large datasets. It is a habit.

*sets NM rows to the NM value of your row with the defined length.

A: You can first group the dataframe by the length column before filling. Only issue is that for the first group in your example limit would be 0 which causes an error, so we can make sure it's at least 1 with max. This might cause unexpected results if there are nan values before the first non-zero value in length but from the given data it's not clear if that can happen.
# make groups
m = df.length.gt(0).cumsum()

# fill the column
df["NM"] = df.groupby(m).apply(
                    lambda f: f.NM.fillna(
                    method="ffill",
                    limit=max(f.length.iloc[0], 1))
).values


text:
Q: Are there any differences between the standing wave diagrams of two non-transposing instruments? For example, a cello and a flute are both non-transposing instruments. Thus, they both have harmonics at the same frequencies. Will there be any differences in their pressure time graphs then?

A: In music, the term "transposing instruments" only refers to the notation, not the physics of how the instrument works.
For instruments that produce a sustained sound at constant amplitude, the sound pressure can always be represented (using Fourier analysis) by "harmonics" which are integer multiples of the fundamental frequency. However the amplitude and relative phase of the harmonics depends on the instrument (and also how it is played) so the pressure-time graphs of the sounds are different.
Note that this Fourier analysis tells you nothing about the "natural" modes of vibration of the instrument, because the sound is produced by a continuous input of energy and the system is undergoing "forced vibration" not "free vibration."
For example, the sound of organ pipes can be described in this way using Fourier analysis, but the description of the harmonics of "open" and "stopped" pipes you find in elementary physics textbooks is a complete work of fiction if applied to real organ pipes, which are not simple cylindrical tubes with the ends either fully open or fully closed. The resonant frequencies of real organ pipes do not follow simple 1:2:3... or 1:3:5... ratios, even approximately.
For instruments that do not produce a sustained sound (piano, guitar, bells, etc). the frequencies of the natural vibration modes of the instrument are not usually in simple integer ratios.
Even for "stretched string" instruments like piano and guitar, the frequencies are only approximately in the ratio 1:2:3:etc, and the small deviations are important in understanding real instruments, rather than the simple idealized mathematical models of them you learn about in a first course on sound and vibration.
For pitched percussion instruments (bells, xylophone, marimba, timpani, etc) the frequencies of the harmonics are not even approximately in simple integer ratios, and the ratios are different for different instruments.


text:
Q: Method in WebApi controller not being matched with appropriate AJAX call My Controller code:
    public List<ContactDTO> GetAllContacts()
    {
        return repository.GetAllContacts().ToList();
    }

    public ContactDTO GetContact(int contactId)
    {
        return repository.GetContact(contactId);
    }

And my ajax call:
            $.ajax({
                method: "GET",
                url: "http://localhost:54185/contacts/details/1",
                dataType: "JSON",
                success: function (data) {
                    callback();
                },
            });

My ajax call to get all contacts works properly:
            $.ajax({
                method: "GET",
                url: "http://localhost:54185/contacts",
                dataType: "JSON",
                success: function (result) {
                    // result is ok
                }
            });

I have edited both RouteConfig and WebApiConfig files, tho I'm not sure I did everything right.
//RouteConfig:
public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

            routes.MapRoute(
                name: "Details",
                url: "contacts/details/{id}",
                defaults: new { controller = "Home", action = "Details", id = UrlParameter.Optional }
            );
        }

And WebApiConfig
public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(name: "contactDetails",
                routeTemplate: "{controller}/details/{id}");
        }

So I'm not sure what I'm missing / have done wrong. With this configuration, first ajax call always falls into GetAllContacts() method

A: In this case you'd do best not to confuse your routing schemes if you're using both MVC and API side by side.  And I'm not sure how GetAllContacts would work in this case, either apply a Route attribute like the previous answerer said or rename your method.
I prefer to keep my API's in a specific taxonomy:
config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}",
                defaults: new {
                    controller = "DefaultApi",
                    id = RouteParameter.Optional }
);

So in your case, keep your controller and keep your action.  Maybe decorate it with [HttpGet] for good measure:
[HttpGet]
public List<ContactDTO> AllContacts()
{
    return repository.GetAllContacts().ToList();
}

And if you are rendering your script in a .CSHTML file you can let Web API render the right path for you:
$.ajax({
    method: "GET",
    url: "@(Url.RouteUrl("DefaultApi", new { httproute = false, controller = "Contacts", action = "AllContacts" }))",
    dataType: "JSON",
    success: function (result) {
        // result is ok
    }
});

A: Try Atribute Routing for better understanding
You need to give full


text:
Q: Rename file in directory it is found I want to find all files that end in file.one.ext and rename them to file.ext
I have managed to get this far, however it then moves the file to the working directory, not the directory it found the file in.
find . -name "file.one.ext" -exec bash -c 'mv "$0" "file.ext"' {} \;

$0 contains the full path and filename, yet how do I get that directory to attach it to the new file name.
I also have rename installed, if that makes things easier. I am on a macOS Sierra.

A: How do I rename a file in directory it's in?
All you are missing is dirname from the command:
find . -name "file.one.ext" -exec bash -c 'mv "$0" "$(dirname $0)/file.ext"' {} \;

Example
mkdir test1 test2
touch test1/file.one.ext test2/file.one.ext
find . -name "file.one.ext" -exec bash -c 'mv "$0" "$(dirname $0)/file.ext"' {} \;
ls test1/ test2/

test1/:
file.ext

test2/:
file.ext

Demo


text:
Q: Escape HTML tags when converting c# view model to javascript model I'm trying to convert the C# Model in razor to javascript model using JsonConvert.SerializeObject.
var brandsCollectionModel = '@(Html.Raw(JsonConvert.SerializeObject(Model)))';

The Model contains a number of properties of a different type.
The problem is that some of these properties contain special characters, such as "<, >".
Unfortunately this causes javascript syntax error:
"SyntaxError: Unexpected token <"
I'm trying to find a way to detect a property that contains special characters and encode it.
I'm using Html.Raw to prevent encoding as I don't want to escape double quotes that are generated when converting Model to JSON string.
I would be thankful for your help.

A: Assign the serialized Model to js variable.
var data = '@JsonConvert.SerializeObject(Model)';

When the Model is Serialized to Json, it contains &quot  instead of " character. So replace it with ", parse it and assign to js variable.
var jsObj = JSON.parse(data.replace(/"/g,'"'));


text:
Q: Posting an answer results in a 404 page when using Chrome So I've typed in my answer, press post, and BAM: 404 Page. Go back (copy my answer) and refresh, the question is there. Try again, BAM: 404 Page.
Here is the question : https://stackoverflow.com/questions/1272494/sort-a-csv-file-by-last-name-with-php
Here is the 404 URL: https://stackoverflow.com/questions/1272494/answer
I also had to switch to Firefox to Post this Question. So I believe it is a bug in Chrome.
I asked it here: https://meta.stackexchange.com/questions/ask
Posted to Here: https://meta.stackexchange.com/questions/ask/post
which ended up to be just a blank Ask Form.
Edit: Using Chrome 3.0.

A: I use Chrome on Linux (dev channel) and three different Windows boxes (1 dev, 2 stable) all day long. I'd notice if it were reliably broken...

A: Just posted and deleted my answer there with no problem in Chrome 2.0.


text:
Q: Alert class ID via document.getElementById I'm trying to load "test.php?id=1" on an alert box using id="bnt_support"
Example:
  test

I did try calling bnt_support directly with document.getElementById but it did not work.

Do I need to call the class MenuItem sprt_05 also?

A:  elements don't have a value. You're trying to get the href, not the value. Because the href property is usually a full URL, you actually need the href attribute, so use this:
document.getElementById('bnt_support').getAttribute("href")

As mentioned before, the href property would be:
document.getElementById('bnt_support').href


text:
Q: Java: Can I initialize a function directly without converting it to a variable? For the first code: findContact(String name) did not return any contact rather it returned "Error in finding contact".
First code didn't work:
public Contacts findContact(String name) {
    for (int i = 0; i < contactsArray.size(); i++) {
        if (contactsArray.get(i).getName().equals(name)) {    // USED IT DIRECTLY
            return contactsArray.get(i);
        } else {
            System.out.println("Error in finding contact");
        }
    }

    return null;
}

For the second code: findContact(String name) returned contact for the same 'name' inputted for first code.
Code below worked:
public Contacts findContact(String name) {
    for (int i = 0; i < contactsArray.size(); i++) {
        Contacts contact = contactsArray.get(i);   // ADDED A CONTACTS VARIABLE
        if (contact.getName().equals(name)) {
            return contactsArray.get(i);
        } else {
            System.out.println("Error in finding contact");
        }
    }

    return null;
}

A: Both of the code blocks are pretty much the same. According to your logic, if first time, the input item is not matched you reach the else condition which is logically wrong. May be, the input passed each time would have been different. And as some of the members suggested, the logic is wrong.
It is not mandatory to assign to a variable as you have tried in the second block.
But using an enhanced for loop makes the code more better.
I suggest the logic to be changes something like the following:
public Contacts findContact(String name) {
    for(Contacts contact: contactsArray){
        if(null!=name && name.equals(contact.getName())){
            return contact;
       }
    }
    System.out.println("Error in finding contact");
    return null;
}

A: use foreach for a clean code
public Contacts findContact(String name) {
    if(name != null) {
       for (Contacts contact : contactsArray) {
          if (name.equals(contact.getName())) {
            return contact;
          }
       }
    }
    System.out.println("Error in finding contact:".concat(name));
    return null;
}

if you are using java 8
public Contacts findContact(String name) {
    Contacts contact = null;
    if(name != null) {
        contact = contactsArray.stream()
          .filter(contactAux -> name.equals(contactAux.getName()))
          .findAny()
          .orElse(null);
    }
    if(contact == null)
        System.out.println("Error in finding contact:".concat(name));
    return contact;
}

A: though I don't really get your intention, slightly modifying the code like below  would help you.
    public Contacts findContact(String name) {
        for (int i = 0; i < contactsArray.size(); i++) {
           if (contactsArray.get(i).getName().equalsIgnoreCase(name)) {
           /*or below line if you wanted to have a relaxed search
            if(contactsArray.get(i).getName().toLowerCase().contains(name.toLowerCase()))
           */
            return contactsArray.get(i);
            }
        }
        System.out.println("Error in finding contact");
        return null;
     }


text:
Q: Calling an API with Promise returns undefined values in JavaScript I'm trying to get the value of the promise, but it says it is undefined every time.
I'm new to JavaScript, so sorry for being so bad...
For the function being called I didn't put the whole code into the post, just the necessary information that it returns four floats. I tested that function.
I updated the code:
async function getClosestSchachtInSeg(
  LON,
  LAT,
  FROMANGLE,
  TOANGLE,
  NS,
  maxCount
) {
  sqlQuery =
    "SELECT *, ST_X(ST_Transform (geom, 4326)) AS LON, ST_Y(ST_Transform (geom, 4326)) AS LAT," +
    " ST_Transform(SCHAECHTE_OWN.geom, 4326) <-> ST_SetSRID(ST_MakePoint(" +
    LON +
    ", " +
    LAT +
    "), 4326)::geometry AS dist " +
    ' FROM public."SCHAECHTE_OWN" SCHAECHTE_OWN ' +
    " WHERE atan((ST_X(ST_Transform (geom, 4326)) - " +
    LON +
    ") /  (ST_Y(ST_Transform (geom, 4326)) - " +
    LAT +
    ")) > " +
    FROMANGLE +
    "*pi()/180" +
    " AND atan((ST_X(ST_Transform (geom, 4326)) - " +
    LON +
    ") /  (ST_Y(ST_Transform (geom, 4326)) - " +
    LAT +
    ")) < " +
    TOANGLE +
    "*pi()/180" +
    " AND ST_Y(ST_Transform (geom, 4326)) " +
    NS +
    " " +
    LAT +
    " ORDER BY dist LIMIT " +
    maxCount +
    ";";

  pool
    .query(sqlQuery)
    .then((results) => {
      if (results.rows.length > 0) {
        for (i = 0; i < results.rows.length; i++) {
          var ResLon = results.rows[i].lon;
          var ResLat = results.rows[i].lat;
          var ResDist = results.rows[i].dist;

          var urlDistance =
            "http://gisdatavm01hw.versatel.local:5001/getShortestPathLonLatDistance/" +
            Math.round(LON * 1000000) / 1000000 +
            "/" +
            Math.round(LAT * 1000000) / 1000000 +
            "/" +
            Math.round(results.rows[i].lon * 1000000) / 1000000 +
            "/" +
            Math.round(results.rows[i].lat * 1000000) / 1000000;

          //console.log(urlDistance);

          fetch(urlDistance)
            .then((response) => response.text())
            .then((body) => {
              //console.log(body);
              Dist = JSON.parse(body)["distance"];
              if (Dist) {
                return 10;
              }
            });
        }
      }
    })
    .catch((err) => console.error("Error executing query", err.stack));
}

async function getClosestSchachtOWNJson12SegNew(request, response) {
  response.setHeader("Access-Control-Allow-Origin", "*");
  response.setHeader("Access-Control-Allow-Credentials", "true");
  response.setHeader(
    "Access-Control-Allow-Methods",
    "GET,HEAD,OPTIONS,POST,PUT"
  );
  response.setHeader(
    "Access-Control-Allow-Headers",
    "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"
  );
  //response.setHeader("Content-Type", "application/json");

  const LON = request.params.LON;
  const LAT = request.params.LAT;
  const maxCount = request.params.maxCount;

  Promise.resolve([
    getClosestSchachtInSeg(LON, LAT, -90, -60, ">=", maxCount),
    getClosestSchachtInSeg(LON, LAT, -60, -30, ">=", maxCount),
    getClosestSchachtInSeg(LON, LAT, -30, 0, ">=", maxCount),
    getClosestSchachtInSeg(LON, LAT, 0, 30, ">=", maxCount),
    getClosestSchachtInSeg(LON, LAT, 30, 60, ">=", maxCount),
    getClosestSchachtInSeg(LON, LAT, 60, 90, ">=", maxCount),
    getClosestSchachtInSeg(LON, LAT, -90, -60, "<", maxCount),
    getClosestSchachtInSeg(LON, LAT, -60, -30, "<", maxCount),
    getClosestSchachtInSeg(LON, LAT, -30, 0, "<", maxCount),
    getClosestSchachtInSeg(LON, LAT, 0, 30, "<", maxCount),
    getClosestSchachtInSeg(LON, LAT, 30, 60, "<", maxCount),
    getClosestSchachtInSeg(LON, LAT, 60, 90, "<", maxCount),
  ]).then((values) => {
    console.log(values);
  });
}

The output is:
[
  Promise { undefined },
  Promise { undefined },
  Promise { undefined },
  Promise { undefined },
  Promise { undefined },
  Promise { undefined },
  Promise { undefined },
  Promise { undefined },
  Promise { undefined },
  Promise { undefined },
  Promise { undefined },
  Promise { undefined }
]

A: You're forgetting an await on the call to the async function getClosestSchachtInSeg.
Change:
const promise1 = new Promise((resolve, reject) => {

  resolve(getClosestSchachtInSeg(LON,LAT,-90,-60,">=",maxCount));

});

promise1.then(result => {

  console.log(result);

  console.log(promise1);

  return result;

})

to:
const result = await getClosestSchachtInSeg(LON, LAT, -90, -60, ">=", maxCount);
console.log(result);

// do what ya gotta do

Also, make getClosestSchachtOWNJson12SegNew an async function (so the awaits above work — you can't use await in a non-async function).


text: Q: How to convert HTTP Cookie into JSON Cookie Hy, I want to know if I have HTTP cookie and want to convert it into a JSON cookie so I can import it into the cookie editor did anyone have any clue how to convert or run an HTTP cookie into JSON Thank u.


text:
Q: numpy save an array of different types to a text file Say I have the following numpy structured array:
>>> a = numpy.array((1, 2.0, 'buckle_my_shoe'),dtype=('i4,f8,a14'))
array((1, 2.0, 'buckle_my_shoe'),
  dtype=[('f0', '<i4'), ('f1', '<f8'), ('f2', 'S14')])

and I want to save it to a single space or tab delimited row in a text file. If the array were all of the same type I could use numpy.savetxt('myfile.dat,myarray,newline=" "). However, this seems to not like mixed data types/structured arrays, for example:
file('myfile.dat', 'a')
numpy.savetxt('myfile.dat',a,newline=" ")

gives this error:
IndexError: tuple index out of range

Can anyone recommend a way of doing this?

A: Edit: For whatever reason I can't seem to be able to leave this answer alone, so here's a cleaner version that doesn't use the csv module unnecessarily. For the record, @askewchan's answer is still better!
a = numpy.array([(1, 2.0, 'buckle_my_shoe'),
                 (3,4.0,'lock_the_door')],dtype=('i4,f8,a14'))
with open('test.txt','w') as f:
     f.write(' '.join([str(item) for sublist in a for item in sublist]))
print open('test.txt','r').read()

Output:
1 2.0 buckle_my_shoe 3 4.0 lock_the_door

A: If you have a zero-d array like your example, then you can just do this:
b = np.array((1, 2.0, 'buckle_my_shoe'),
         dtype=[('f0', '<i4'), ('f1', '<f8'), ('f2', 'S14')])

with open('myfile.dat','w') as f:
    for el in b[()]:
        f.write(str(el)+' ') # or `f.write(repr(el)+' ') to keep the quote marks

This works by accessing the elements of 0d arrays using [()]:
>>> b.ndim
0

>>> b[0]
IndexError: 0-d arrays cannot be indexed

>>> b[()]
(1, 2.0, 'buckle_my_shoe')

If you are using numpy arrays with zero dimensions regularly, in order to have the complex dtype, I might suggested the NamedTuple from collections.
>>> import collections
>>> A = collections.namedtuple('A', ['id', 'val', 'phrase'])
>>> a = A(1, 2.0, 'buckle_my_shoe')

>>> a
A(id=1, val=2.0, phrase='buckle_my_shoe')
>>> a.id
1
>>> a.val
2.0
>>> a.phrase
'buckle_my_shoe'

with open('myfile.dat','w') as f:
    for el in a:
        f.write(repr(el)+' ')

If the array has more than one element:
a = np.array([(1, 2.0, 'buckle_my_shoe'),
              (3, 4.0, 'lock_the_door')],
        dtype=('i4, f8, a14'))

I'm not sure what exactly you want your file to look like.  If you want the space-separated tuples, this is the best way I think:
with open('myfile.dat','w') as f:
    for row in a:
        f.write(repr(row)+' ')

which results in a file like:
(1, 2.0, 'buckle_my_shoe') (3, 4.0, 'lock_the_door')

Perhaps you wanted to have no commas or parentheses, in which case you can do:
with open('myfile.dat','w') as f:
    for row in a:
        for el in row:
            f.write(str(el)+' ')

which gives this file:
1 2.0 buckle_my_shoe 3 4.0 lock_the_door

Use repr to keep the qutoes around the strings
with open('myfile.dat','w') as f:
    for row in a:
        for el in row:
            f.write(repr(el)+' ')

which gives this file:
1 2.0 'buckle_my_shoe' 3 4.0 'lock_the_door'

Bonus: If your dtype has field names, you can print those too:
a.dtype.names = "index value phrase".split()
a.dtype
#dtype([('index', '<i4'), ('value', '<f8'), ('phrase', 'S14')])

with open('myfile.dat','w') as f:
    for name in a.dtype.names:
        f.write(name + ' ') # or write(repr(name)) to keep the quote marks
    for row in a:
        for el in row:
            f.write(repr(el)+' ')

Note, if you copy these files be warned I used 'w' not 'a', so that I could overwrite each one in my test cases.


text:
Q: Python: log myobj.myprop even if myobj or myobj.myprop are None? I'm looking for a shortcut for:
name = ''
if myobj not None and myobj.name not None:
  name = myobj.name

date = ''
if myobj not None and myobj.date not None:
  date = myobj.date

logging.info('Something happened with %s at %s', name, date)

Something like:
logging.info('Something happened with %s at %s', none_as_empty_str(myobj.name), none_as_empty_str(myobj.date))

Any idea? Thank you!

A: If you want something relatively short, you could use:
myobj and myobj.name or ''

If myobj or myobj.name is None (or otherwise falsey), this will produce ''.
Otherwise it will produce myobj.name.
Alternatively, your none_as_empty_str function is viable as long as you defer accessing the attribute until inside the function, or access it indirectly. That way, if myobj is None, you can get your empty string instead of an exception:
def none_as_empty_str(obj, attr):
    return getattr(obj, attr, None) or ''

logging.info('Something happened with %s at %s',
             none_as_empty_str(myobj, 'name'),
             none_as_empty_str(myobj, 'date'))


text:
Q: Could not reach external www. Host is not querying for A record, because the domains matches Have a problem where i could not reach my external www as i created company domain with the same name.
I can reach external site from all other locations, but not from my domain, because domain name matches and host is not even requesting A record from DNS.
What to do ?

A: Configure your domain to respond to this external www. If you want to be resolved only from inside you can use split DNS.
Regards


text:
Q: stub a constant in a Grape api RSpec test Say I have a constant defined in a Grape::API class:
class Activities < Grape::API
  MAX_ALLOWED = 50000
  ...
end

And in the endpoint desc:
params do
  requires :data, type: Array, allow_blank: false, array_length: MAX_ALLOWED
end

I want to write a spec (using RSpec) to test the array_length option for the endpoint. I would like to stub the MAX_ALLOWED constant since I don't want to actually generate 50k of dummy data.
I tried stub_const(API::V3::Resources::Activities::MAX_ALLOWED, 3)
but got an error: NoMethodError: undefined method 'sub' for 40000:Fixnum
I also tried stub_const('API::V3::Resources::Activities::MAX_ALLOWED', 3)
but that just didn't work.
Lastly, I tried:
before do
  allow_any_instance_of(API::V3::Resources::Activities).to receive(:MAX_ALLOWED).and_return(1)
end

and it also didn't work.
EDIT: also tried allow instead of allow_any_instance_of with same result.
EDIT 2: here's the failing spec:
context 'with more than 50,000 contacts' do
  let(:options) {{ 'CONTENT_TYPE' => 'application/json' }}

  # contacts_api, uri, resource, and request are defined elsewhere
  before { contacts_api :post, "#{uri}#{resource}", request.to_json, options }

  # Also tried this instead of stub_const:
  # before do
  #  allow_any_instance_of(API::V3::Resources::Activities).to receive(:MAX_ALLOWED).and_return(1)
  # end

  it 'returns a 400' do
    stub_const('API::V3::Resources::Activities::MAX_ALLOWED', 3)
    expect(response.status).to eq(400)
    expect(resp_body['error_key']).to eq('api error')
    expect(resp_body['error_message']).to eq('too many contacts')
  end
end

EDIT 3: with the request in the same it block as the stub_const (still fails):
it 'returns a 400' do
  stub_const('API::V3::Resources::Activities::MAX_ALLOWED', 3) # this doesn't work
  contacts_api :post, "#{uri}#{resource}", request.to_json, options
  expect(response.status).to eq(400)
  expect(resp_body['error_key']).to eq('contacts.api.bad_request')
  expect(resp_body['error_message']).to eq('too many contacts')
end

Any idea how to stub a constant defined in a Grape::API class for an RSpec test?

A: Stubbing needs to be done before your request. In this case, you can put it into a before block above the POST.
before { stub_const('API::V3::Resources::Activities::MAX_ALLOWED', 3) }
before { contacts_api :post, "#{uri}#{resource}", request.to_json, options }


text:
Q: Cell border not showing in IE9 when filter gradient is applied to cells I'm creating a grid list, using a CSS gradient applied in the title row, i.e. the first row. Also there is border applied.
Before applying the Gradient filter the border was showing in all browsers, but after applied the gradient filter, IE hides the border! Others browsers are ok.
CSS code below:
.list tr.titlerow, .list .titlerow th {
    border: 1px solid #a0a0a0;
    height:25px;
    padding:2px;
    filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#EBEBEB', endColorstr='#ffffff');/*For IE7-8-9*/
    background: -moz-linear-gradient(top, #EBEBEB 0%, #fff 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#EBEBEB), color-stop(100%,#fff)); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top, #EBEBEB 0%,#fff 100%); /* Chrome10+,Safari5.1+ */
    background: -ms-linear-gradient(top, #EBEBEB 0%,#fff 100%); /* IE10+ */
    background: -o-linear-gradient(top, #EBEBEB 0%,#fff 100%); /* Chrome10+,Safari5.1+ */

}

Can anyone please help me to fix this?

A: IE filters can often completely mess up other things for no good reason. Sometimes applying one filter kills another filter - they don't even play nicely with each other, let alone proper CSS!
Instead of using a filter and trying to do things the proper way, I would just fall back to an image-based gradient for IE using conditional comments or some other similar mechanism.

A: Try this way:-
    .list tr.titlerow, .list .titlerow th
    {
        border: 1px solid #a0a0a0;
        height:25px;
        padding:2px;
        background: -moz-linear-gradient(top, #EBEBEB 0%, #fff 100%); /* FF3.6+ */
        background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#EBEBEB), color-stop(100%,#fff)); /* Chrome,Safari4+ */
        background: -webkit-linear-gradient(top, #EBEBEB 0%,#fff 100%); /* Chrome10+,Safari5.1+ */
        background: -ms-linear-gradient(top, #EBEBEB 0%,#fff 100%); /* IE10+ */
        background: -o-linear-gradient(top, #EBEBEB 0%,#fff 100%); /* Chrome10+,Safari5.1+
*/
        filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#EBEBEB', endColorstr='#ffffff'); /* IE6 & IE7 */
        -ms-filter: "progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#EBEBEB', endColorstr='#ffffff')";    /* IE8 */

    }

A: Just add position:relative;

.container
{
    display: table;
    background-color: lightblue;
    border-spacing: 5px 0;
}

.container > a
{
    display: table-cell;
    width: 60px;
    height: 25px;

    border-style: solid;
    border-width: 1px;

 border-color:#adae9c;
 background: #e4e7dd; /* Old browsers */
 background: -moz-linear-gradient(top,  #fefefe 0%, #e4e7dd 100%); /* FF3.6+ */
 background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#fefefe), color-stop(100%,#e4e7dd)); /* Chrome,Safari4+ */
 background: -webkit-linear-gradient(top,  #fefefe 0%,#e4e7dd 100%); /* Chrome10+,Safari5.1+ */
 background: -o-linear-gradient(top,  #fefefe 0%,#e4e7dd 100%); /* Opera 11.10+ */
 background: -ms-linear-gradient(top,  #fefefe 0%,#e4e7dd 100%); /* IE10+ */
 background: linear-gradient(to bottom,  #fefefe 0%,#e4e7dd 100%); /* W3C */

    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fefefe',endColorstr='#e4e7dd',GradientType=0 ); /* IE6-9 */
    /*get around bug with IE9 that won't render the border if combined with table-cell and using a filter*/
    position: relative;
}

    test1
    test2


text:
Q: SQL Query On Date When Type Is VARCHAR I'm trying to query a database with a between 2 dates... The problem is the column that I am querying contains dates that are currently formatted like this "01/01/2014" (dd/mm/yyyy) with a column type of VARCHAR.
At the moment, I can't convert the column to a date type.
Basically when I query the table because it's not set to date type the between query doesn't return the correct rows...
Has anyone else come across this problem, is there something I can change within the query?
$this->db->where('IssueDate >=', '02/12/2013');
$this->db->where('IssueDate <=', '22/01/2014');
$query = $this->db->get('MYTABLE');

Thanks guys.

A: The solution is to use str_to_date():
$this->db->where("str_to_date(IssueDate, '%d/%m/%Y') >=", "'2013-12-92'");
$this->db->where("str_to_date(IssueDate, '%d/%m/%Y') <=", "'2014-01-22'");
$

You may not have any control over the database.  But you do have control over your own constants.  You should get used to the ISO standard YYYY-MM-DD for such constants -- unambiguous and accepted correctly by most databases.

A: I might suggest creating a view on the table in the database that transforms the string date columns you have into the following format...   YYYYMMDD
That format is sortable and can easily be compared versus other similar formatted dates - you can even do date arithmetic with it.
Keep in mind that a view does not copy the table or add any performance overhead.  It is often a good idea to access any table through a view even if initially you do not need to perform any manipulations on the underlying table - it will help if you later find you do need to perform them.

A: use BETWEEN clause with STR_TO_DATE(). Check below code:-
$wh = STR_TO_DATE(`IssueDate`,'%d/%m/%Y')." between '02/12/2013' and '22/01/2014'";
$this->db->where($wh);

Expect it'll give You perfect result.


text:
Q: use one() within a for loop jquery for (var i = 0; i < res.length; i++) {

    if (res[i] != 'a' && res[i] != '-b') {

    } else {
        // alert will triger multiple times here
        alert();
    }

}

I loop through an array to check something, how can I run once in the else statement? if I put a function there, it will trigger multiple times.

A: You need to break; after your else-action.

A: Try this:
for (var i = 0; i < res.length; i++) {

    if (res[i] != 'a' && res[i] != '-b') {

    } else {
        // alert will triger multiple times here
        alert();
        break;
    }

}

A: You can use a flag to indicate whether the else block was executed, if so don't execute it again
var run = true;
for (var i = 0; i < res.length; i++) {

    if (res[i] != 'a' && res[i] != '-b') {

    } else if (run) {
        // alert will triger multiple times here
        alert();
        run = false;
    }

}

A: You could use a simple boolean flag:
// Introduce the flag before your for loop
var process = true;
for (var i = 0; i < res.length; i++) {

    if (res[i] != 'a' && res[i] != '-b') {

    } else if(process) {
        // alert will triger multiple times here
        alert();
        process = false; // Reset the process flag
    }

}


text:
Q: _wfopen equivalent under Mac OS X I'm looking to the equivalent of Windows _wfopen() under Mac OS X. Any idea?
I need this in order to port a Windows library that uses wchar* for its File interface. As this is intended to be a cross-platform library, I am unable to rely on how the client application will get the file path and give it to the library.

A: You just want to open a file handle using a path that may contain Unicode characters, right?  Just pass the path in filesystem representation to fopen.

*

*If the path came from the stock Mac OS X frameworks (for example, an Open panel whether Carbon or Cocoa), you won't need to do any conversion on it and will be able to use it as-is.

*If you're generating part of the path yourself, you should create a CFStringRef from your path and then get that in filesystem representation to pass to POSIX APIs like open or fopen.
Generally speaking, you won't have to do a lot of that for most applications.  For example, many applications may have auxiliary data files stored the user's Application Support directory, but as long as the names of those files are ASCII, and you use standard Mac OS X APIs to locate the user's Application Support directory, you don't need to do a bunch of paranoid conversion of a path constructed with those two components.
Edited to add:  I would strongly caution against arbitrarily converting everything to UTF-8 using something like wcstombs because filesystem encoding is not necessarily identical to the generated UTF-8.  Mac OS X and Windows both use specific (but different) canonical decomposition rules for the encoding used in filesystem paths.
For example, they need to decide whether "é" will be stored as one or two code units (either LATIN SMALL LETTER E WITH ACUTE or LATIN SMALL LETTER E followed by COMBINING ACUTE ACCENT).  These will result in two different — and different-length — byte sequences, and both Mac OS X and Windows work to avoid putting multiple files with the same name (as the user perceives them) in the same directory.
The rules for how to perform this canonical decomposition can get pretty hairy, so rather than try to implement it yourself it's best to leave it to the functions the system frameworks have provided for you to do the heavy lifting.

A: @JKP:
Not all functions in MacOS X accept UTF8, but filenames and filepaths may be UTF8, thus all POSIX functions dealing with file access (open, fopen, stat, etc.) accept UTF8.
See here. Quote:

How a file name looks at the API level
  depends on the API. Current Carbon
  APIs handle file names as an array of
  UTF-16 characters; POSIX ones handle
  them as an array of UTF-8, which is
  why UTF-8 works well in Terminal. How
  it's stored on disk depends on the
  disk format; HFS+ uses UTF-16, but
  that's not important in most cases.

Some other POSIX functions handle UTF8 as well. E.g. functions dealing with user names, group names or user passwords use UTF8 to store the information (thus a user name can be Japanese and your password can be Chinese, no problem).
But not all handle UTF8. E.g. for all string functions an UTF8 string is just a normal C String and characters above 126 have no special meaning. They don't understand the concept of multiple bytes (chars in C) forming a single Unicode character. How other APIs handle char * pointer being passed to them is different from API to API. However, as a rule as the thumb you can say:
Either the function only accepts C strings with pure ASCII characters (only in the range 0 to 126) or it will accept UTF8. Usually functions don't allow characters above 126 and interpret them in any other encoding than UTF8. If this really was the case, it is documented and then there must be a way to pass the encoding along with the string.

A: POSIX API in Mac OS X are usable with UTF-8 strings. In order to convert a wchar_t string to UTF-8, it is possible to use the CoreFoundation framework from Mac OS X.
Here is a class that will wrap an UTF-8 generated string from a wchar_t string.
class Utf8
{
public:
    Utf8(const wchar_t* wsz): m_utf8(NULL)
    {
        // OS X uses 32-bit wchar
        const int bytes = wcslen(wsz) * sizeof(wchar_t);
        // comp_bLittleEndian is in the lib I use in order to detect PowerPC/Intel
        CFStringEncoding encoding = comp_bLittleEndian ? kCFStringEncodingUTF32LE
                                                       : kCFStringEncodingUTF32BE;
        CFStringRef str = CFStringCreateWithBytesNoCopy(NULL,
                                                       (const UInt8*)wsz, bytes,
                                                        encoding, false,
                                                        kCFAllocatorNull
                                                        );

        const int bytesUtf8 = CFStringGetMaximumSizeOfFileSystemRepresentation(str);
        m_utf8 = new char[bytesUtf8];
        CFStringGetFileSystemRepresentation(str, m_utf8, bytesUtf8);
        CFRelease(str);
    }

    ~Utf8()
    {
        if( m_utf8 )
        {
            delete[] m_utf8;
        }
    }

public:
    operator const char*() const { return m_utf8; }

private:
    char* m_utf8;
};

Usage:
const wchar_t wsz = L"Here is some Unicode content: éà€œæ";
const Utf8 utf8 = wsz;
FILE* file = fopen(utf8, "r");

This will work for reading or writing files.

A: If you're using Cocoa it's fairly easy with NSString. Just load the UTF16 data in using -initWithBytes:length:encoding: (or perhaps -initWithCString:encoding:) and then get a UTF8 version by calling UTF8String on the result.  Then, just call fopen with your new UTF8 string as the param.
You can definitely call fopen with a UTF-8 string, regardless of language - can't help with C++ on OSX though - sorry.

A: I have read file name from configuration UTF8 file through wifstream (it uses wchar_t buffer).
Mac implementation is different from Linux and Windows.
wifstream reads each byte from file to separate wchar_t cell in the buffer. So we have 3 empty bytes, although open requires char string. Thus programmer can use wcstombs function to convert wide character string to multi-byte string.
The API supports UTF8. For better understanding use memory watcher and hex editor for your file.


text:
Q: How to backup a SharePoint list to Excel or CSV so that 'Choice' column (with multiple selections) values are displayed as text? Environment
I created a Custom List via New > App > Custom List.
I created columns and added entries via the form associated with the list.
Some of the columns are of type Choice and configured to allow multiple selections.
For example:
Service Type:

 - Groceries - Apples
 - Groceries - Oranges
 - Groceries - General

Desired Behaviour
Copy a SharePoint list into a CSV file via a recurring Microsoft Flow based on this template.
I have only chosen the CSV format for the backup because I thought it would be easier to set up the related flow - if an Excel spreadsheet backup could be created, that would be ideal.
Current Behaviour
When I open the CSV in Excel, a single Choice column has turned into 4 columns:
ServiceType

ServiceType@odata.type

ServiceType#Id

ServiceType#Id@odata.type

with the corresponding values of:
[{"@odata.type":"#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference","Id":2,"Value":"Groceries - General"}]

#Collection(Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference)

[2]

#Collection(Int64)

Question
How can I ensure that:

*

*Only a single column is displayed for each Choice column

*Only the values of the columns are displayed, rather than all the Microsoft 'markup' text
Flow:

A: For your requirement, i will suggest directly export sharepoint list to excel
You can always update the file to the latest list via refresh all, no need to update it everyday.

A: Short Answer
Use this:
xpath(xml(json(concat('{"root":{"choices":', item()?['MyChoiceColumnInternalName'] , '}}'))), '/root/choices/Value/text()')

or this:
join(xpath(xml(json(concat('{"root":{"choices":', item()?['MyChoiceColumnInternalName'] , '}}'))), '/root/choices/Value/text()'), ';#')

Long Answer
I thought it would be helpful to:

*

*create a list that contained all column types

*add an entry

*export the list to CSV table

*see what the exported values were
These are the columns:

Edit:  Things I learned after posting this:

*

*Column names have a 32 characters limit 'internally', longer names are truncated (src)

*Changing the column name does not change the 'internal' column name (src)

+--------------------------------------+------------------------+
|                Column                |          Type          |
+--------------------------------------+------------------------+
| Title                                | Single line of text    |
| MySingleLineOfTextColumn             | Single line of text    |
| MyMultipleLinesOfTextColumn          | Multiple lines of text |
| MyNumberColumn                       | Number                 |
| MyYesNoColumn                        | Yes/No                 |
| MyPersonColumn                       | Person or Group        |
| MyDateColumn                         | Date and Time          |
| MyChoiceColumnMultiWithSelections    | Choice                 |
| MyChoiceColumnMultiWithoutSelections | Choice                 |
| MyChoiceColumnSingleWithSelection    | Choice                 |
| MyChoiceColumnSingleWithoutSelection | Choice                 |
| MyHyperlinkColumn                    | Hyperlink or Picture   |
| MyPictureColumn                      | Hyperlink or Picture   |
| MyCurrencyColumn                     | Currency               |
| MyLocationColumn                     | Location               |
| Modified                             | Date and Time          |
| Created                              | Date and Time          |
| Created By                           | Person or Group        |
| Modified By                          | Person or Group        |
+--------------------------------------+------------------------+

So first, I switched to the Custom option in the Create CSV Table section.
The stars below indicate dynamic content variables that had 'extended' versions available because their value is an object, not a string, ie:
MyLocationColumn: Name
MyPersonColumn DisplayName
MyChoiceColumnSingleWithSelection Value
MyChoiceColumnSingleWithoutSelection Value
Modified By DisplayName
Created By DisplayName

When I tested the flow, these were the results in the Create CSV Table step:

JSON (the INPUTS > From section):
The Get items step produces an array of objects, where each object is an item in the list.
You can see below which columns have a string, object or array as a value.
The column type of Choice (multiple selections allowed) has the latter - ie an array of objects.
[
  {
    "@odata.etag": "\"6\"",
    "ItemInternalId": "2",
    "ID": 2,
    "Title": "Test",
    "MySingleLineOfTextColumn": "Here is a single line of text",
    "MyMultipleLinesOfTextColumn": "Here\nAre\nMultiple\nLines\nOf\nText",
    "MyNumberColumn": 5,
    "MyYesNoColumn": true,
    "MyPersonColumn": {
      "@odata.type": "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedUser",
      "Claims": "i:0#.f|membership|info@mydomain.onmicrosoft.com",
      "DisplayName": "John Smith",
      "Email": "info@mydomain.onmicrosoft.com",
      "Picture": "https://mydomain.sharepoint.com/sites/mydomain/_layouts/15/UserPhoto.aspx?Size=L&AccountName=info@mydomain.onmicrosoft.com",
      "Department": null,
      "JobTitle": null
    },
    "MyPersonColumn#Claims": "i:0#.f|membership|info@mydomain.onmicrosoft.com",
    "MyDateColumn": "2020-04-30",
    "MyChoiceColumnMultiWithSelection": [
      {
        "@odata.type": "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference",
        "Id": 0,
        "Value": "Choice 1"
      },
      {
        "@odata.type": "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference",
        "Id": 1,
        "Value": "Choice 2"
      },
      {
        "@odata.type": "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference",
        "Id": 2,
        "Value": "Choice 3"
      }
    ],
    "MyChoiceColumnMultiWithSelection@odata.type": "#Collection(Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference)",
    "MyChoiceColumnMultiWithSelection#Id": [
      0,
      1,
      2
    ],
    "MyChoiceColumnMultiWithSelection#Id@odata.type": "#Collection(Int64)",
    "MyChoiceColumnMultiWithoutSelect": [],
    "MyChoiceColumnMultiWithoutSelect@odata.type": "#Collection(Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference)",
    "MyChoiceColumnMultiWithoutSelect#Id": [],
    "MyChoiceColumnMultiWithoutSelect#Id@odata.type": "#Collection(Int64)",
    "MyChoiceColumnSingleWithSelectio": {
      "@odata.type": "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference",
      "Id": 0,
      "Value": "Choice 1"
    },
    "MyChoiceColumnSingleWithSelectio#Id": 0,
    "MyHyperlinkColumn": "https://www.google.com",
    "MyPictureColumn": "https://i.picsum.photos/id/237/200/300.jpg",
    "MyCurrencyColumn": 20,
    "CountryOrRegion": "Australia",
    "State": "NSW",
    "City": "Sydney",
    "PostalCode": "2000",
    "Street": "100 Test St",
    "DispName": "100 Test St, Sydney, NSW 2000",
    "Modified": "2020-04-30T08:42:27Z",
    "Created": "2020-04-30T07:17:22Z",
    "Author": {
      "@odata.type": "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedUser",
      "Claims": "i:0#.f|membership|info@mydomain.onmicrosoft.com",
      "DisplayName": "John Smith",
      "Email": "info@mydomain.onmicrosoft.com",
      "Picture": "https://mydomain.sharepoint.com/sites/mydomain/_layouts/15/UserPhoto.aspx?Size=L&AccountName=info@mydomain.onmicrosoft.com",
      "Department": null,
      "JobTitle": null
    },
    "Author#Claims": "i:0#.f|membership|info@mydomain.onmicrosoft.com",
    "Editor": {
      "@odata.type": "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedUser",
      "Claims": "i:0#.f|membership|info@mydomain.onmicrosoft.com",
      "DisplayName": "John Smith",
      "Email": "info@mydomain.onmicrosoft.com",
      "Picture": "https://mydomain.sharepoint.com/sites/mydomain/_layouts/15/UserPhoto.aspx?Size=L&AccountName=info@mydomain.onmicrosoft.com",
      "Department": null,
      "JobTitle": null
    },
    "Editor#Claims": "i:0#.f|membership|info@mydomain.onmicrosoft.com",
    "{Identifier}": "Lists%252fMy%2bAll%2bColumn%2bTypes%2bList%252f2_.000",
    "{IsFolder}": false,
    "{Thumbnail}": {
      "Large": null,
      "Medium": null,
      "Small": null
    },
    "{Link}": "https://mydomain.sharepoint.com/sites/mydomain/_layouts/15/listform.aspx?PageType=4&ListId=5aaeae22-ccf3-48ba-a88b-4130b4293d9f&ID=2&ContentTypeID=0x0100C770D8569664E542BC4A1154C9A4D48E",
    "{Name}": "Test",
    "{FilenameWithExtension}": "Test",
    "{Path}": "Lists/My All Column Types List/",
    "{FullPath}": "Lists/My All Column Types List/2_.000",
    "{HasAttachments}": false,
    "{VersionNumber}": "1.0"
  }
]

Text (the OUTPUTS > Body section):
Title,MySingleLineOfTextColumn,MyMultipleLinesOfTextColumn,MyNumberColumn,MyYesNoColumn,MyPersonColumn,MyDateColumn,MyChoiceColumnMultiWithSelections,MyChoiceColumnMultiWithoutSelections,MyChoiceColumnSingleWithSelection,MyChoiceColumnSingleWithoutSelection,MyHyperlinkColumn,MyPictureColumn,MyCurrencyColumn,MyLocationColumn,Modified,Modified By,Created,Created By
Test,Here is a single line of text,"Here
Are
Multiple
Lines
Of
Text",5,True,John Smith,2020-04-30,"[{""@odata.type"":""#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference"",""Id"":0,""Value"":""Choice 1""},{""@odata.type"":""#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference"",""Id"":1,""Value"":""Choice 2""},{""@odata.type"":""#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference"",""Id"":2,""Value"":""Choice 3""}]",[],Choice 1,,https://www.google.com,https://i.picsum.photos/id/237/200/300.jpg,20,"100 Test St, Sydney, NSW 2000",2020-04-30T08:42:27Z,John Smith,2020-04-30T07:17:22Z,John Smith

Final output displayed in CSV file is therefore:
+--------------------------------------+------------------------+------------------+
|                Column                |          Type          |      Output      |
+--------------------------------------+------------------------+------------------+
| Title                                | Single line of text    | Text             |
| MySingleLineOfTextColumn             | Single line of text    | Text             |
| MyMultipleLinesOfTextColumn          | Multiple lines of text | Text             |
| MyNumberColumn                       | Number                 | Text             |
| MyYesNoColumn                        | Yes/No                 | Text             |
| MyPersonColumn                       | Person or Group        | Text***          |
| MyDateColumn                         | Date and Time          | Text             |
| MyChoiceColumnMultiWithSelections    | Choice                 | Array of Objects |
| MyChoiceColumnMultiWithoutSelections | Choice                 | Array (Empty)    |
| MyChoiceColumnSingleWithSelection    | Choice                 | Text***          |
| MyChoiceColumnSingleWithoutSelection | Choice                 | Text***(Blank)   |
| MyHyperlinkColumn                    | Hyperlink or Picture   | Text             |
| MyPictureColumn                      | Hyperlink or Picture   | Text             |
| MyCurrencyColumn                     | Currency               | Text             |
| MyLocationColumn                     | Location               | Text***          |
| Modified                             | Date and Time          | Text             |
| Created                              | Date and Time          | Text             |
| Created By                           | Person or Group        | Text***          |
| Modified By                          | Person or Group        | Text***          |
+--------------------------------------+------------------------+------------------+

*** indicates an 'extended' dynamic variable was used.
Conclusion
You can get a text output for most column types, however Choice (multiselection) is different as its value is an array of objects:
[{"@odata.type":"#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference","Id":0,"Value":"Choice 1"},{"@odata.type":"#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference","Id":1,"Value":"Choice 2"},{"@odata.type":"#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference","Id":2,"Value":"Choice 3"}]

Choice columns (without multiple selections allowed) have the dynamic variable ColumnName Value available because their value is an object.
Solution
Choice column (with multiple selections allowed) can be accessed using an expression like this:
xpath(xml(json(concat('{"root":{"choices":', item()?['MyChoiceColumnInternalName'] , '}}'))), '/root/choices/Value/text()')

which will produce an array like this (if selections have been made):
["Choice 1","Choice 2"]

or an empty array if no selections have been made:
[]

This approach is mentioned in an answer to this post:
https://powerusers.microsoft.com/t5/Building-Flows/Flow-get-multiple-values-from-sharepoint-column-for-CSV-table/td-p/126853
Explanation of solution
In case it helps anyone visualising what the xpath expression does in the solution provided:
var concatenated_string = '{"root":{"choices":' + '[{"@odata.type":"#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference","Id":0,"Value":"Choice 1"},{"@odata.type":"#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference","Id":1,"Value":"Choice 2"},{"@odata.type":"#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference","Id":2,"Value":"Choice 3"}]' + '}}';

/*

produces a string:

{"root":{"choices":[{"@odata.type":"#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference","Id":0,"Value":"Choice 1"},{"@odata.type":"#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference","Id":1,"Value":"Choice 2"},{"@odata.type":"#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference","Id":2,"Value":"Choice 3"}]}}

*/

var json_concatenated_string = JSON.parse(concatenated_string);

/*

produces an object:

{
  "root": {
    "choices": [
      {
        "@odata.type": "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference",
        "Id": 0,
        "Value": "Choice 1"
      },
      {
        "@odata.type": "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference",
        "Id": 1,
        "Value": "Choice 2"
      },
      {
        "@odata.type": "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference",
        "Id": 2,
        "Value": "Choice 3"
      }
    ]
  }
}

*/

var my_xml = json2xml(json_concatenated_string);

/*

produces xml:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <choices odata.type="#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference">
      <Id>0</Id>
      <Value>Choice 1</Value>
   </choices>
   <choices odata.type="#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference">
      <Id>1</Id>
      <Value>Choice 2</Value>
   </choices>
   <choices odata.type="#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference">
      <Id>2</Id>
      <Value>Choice 3</Value>
   </choices>
</root>
*/

/*

xpath(xml, '/root/choices/Value/text()')

get's each Choice's 'Value' property and returns an array of matches, eg:

["Choice 1","Choice 2","Choice 3"]

see:  https://docs.microsoft.com/en-gb/azure/logic-apps/workflow-definition-language-functions-reference#xpath

*/

// function to convert JSON to XML
/*  This work is licensed under Creative Commons GNU LGPL License.

    License: http://creativecommons.org/licenses/LGPL/2.1/
   Version: 0.9
    Author:  Stefan Goessner/2006
    Web:     http://goessner.net/
*/
function json2xml(o, tab) {
   var toXml = function(v, name, ind) {
      var xml = "";
      if (v instanceof Array) {
         for (var i=0, n=v.length; i<n; i++)
            xml += ind + toXml(v[i], name, ind+"\t") + "\n";
      }
      else if (typeof(v) == "object") {
         var hasChild = false;
         xml += ind + "<" + name;
         for (var m in v) {
            if (m.charAt(0) == "@")
               xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\"";
            else
               hasChild = true;
         }
         xml += hasChild ? ">" : "/>";
         if (hasChild) {
            for (var m in v) {
               if (m == "#text")
                  xml += v[m];
               else if (m == "#cdata")
                  xml += "<![CDATA[" + v[m] + "]]>";
               else if (m.charAt(0) != "@")
                  xml += toXml(v[m], m, ind+"\t");
            }
            xml += (xml.charAt(xml.length-1)=="\n"?ind:"") + "</" + name + ">";
         }
      }
      else {
         xml += ind + "<" + name + ">" + v.toString() +  "</" + name + ">";
      }
      return xml;
   }, xml="";
   for (var m in o)
      xml += toXml(o[m], m, "");
   return tab ? xml.replace(/\t/g, tab) : xml.replace(/\t|\n/g, "");
}

Bonus
If you want to output this (a value that can be imported back into a SharePoint list as a Choice (multiple selections allowed) value):
Choice 1;#Choice 2;#Choice 3

Wrap the xpath in a join:
join(xpath(xml(json(concat('{"root":{"choices":', item()?['MyChoiceColumnInternalName'] , '}}'))), '/root/choices/Value/text()'), ';#')


text:
Q: TypeError: Cannot read property 'stateUpdate' (Which is a function) of undefined / Passing data from Parent to child I'm having an issue of passing a function from parent to child component in react js.
I have tried to pass the vale to the component as props but it is showing the type error as defined in the question. i am not able to figure out why is it happening.
Is it because of mapping, if so how to solve it because mapping is important.
Parent Component:
stateUpdate(){
      alert("hi");
    }
    render() {

          const tabList =  this.state.productMapData.map(function(object, i){
            return <TableList obj={object} ids = {productRegistrationArrId} key={i}

Error here:
 parent= {this.stateUpdate.bind(this)}></TableList>
              })
        return (
          <div>
            <div style={{ marginTop: 10, marginLeft: "10%" }}>
            <Link to="/api/productregistration" className="btn btn-info" onClick = {this.onDeleteDb} >
                Back to List
            </Link>

Child Component:
onUpdate(){
        this.props.parent;
    }

A: In parent stateUpdate function declare using arrow function then you may not get this issue. I have mentioned sample code below please find it
stateUpdate =()=> {
  alert("hi");
}

and in child component in update function you have to call parent function like
onUpdate=()=>{
        this.props.parent();
       // here you have to change parent to parent()
    }


text:
Q: OSMDroid memory consumption in offline/online mode I'm making app based on the osmdroid sample map viewer (osmdroid-4.3) and I have some performance problems with osm fragment.
I use unpacked offline MapQuest tiles.
I've noticed this strange memory consumption in offline mode, look at screen please. Memory graph becomes flat after switching to online mode. And logcat spamming all the time in offline about GC stuff.
http://i.stack.imgur.com/IowAq.jpg
Also, when I switch it back to offline - nothing happens until I scroll the map, and again this problem appears.
App feels laggy because of this thing. Any advice? Is it normal for osmdroid or I did something wrong?
============== EDIT ===============
So I did a short research here and made heap dump. But unfortunately I can understand nothing and hope someone can guide me.
The MAT said me this things about possible leaks:
Suspect #1 is
One instance of "org.osmdroid.views.MapView" loaded by "dalvik.system.PathClassLoader @ 0x12c7be00" occupies 9,029,024 (17.58%) bytes. The memory is accumulated in one instance of "org.osmdroid.tileprovider.LRUMapTileCache" loaded by "dalvik.system.PathClassLoader @ 0x12c7be00".

Keywords
dalvik.system.PathClassLoader @ 0x12c7be00
org.osmdroid.tileprovider.LRUMapTileCache
org.osmdroid.views.MapView

Suspect #2
One instance of "android.widget.RelativeLayout" loaded by "<system class loader>" occupies 8,859,712 (17.25%) bytes. The memory is accumulated in one instance of "org.osmdroid.tileprovider.LRUMapTileCache" loaded by "dalvik.system.PathClassLoader @ 0x12c7be00".

Keywords
android.widget.RelativeLayout
dalvik.system.PathClassLoader @ 0x12c7be00
org.osmdroid.tileprovider.LRUMapTileCache

Suspect #3
36 instances of "byte[]", loaded by "<system class loader>" occupy 9,803,328 (19.09%) bytes.

Biggest instances:
•byte[1769472] @ 0xa294f000 ................................................................................................................................................................................................................................................................... - 1,769,488 (3.45%) bytes.

Keywords
byte[]

I can give any additional information from this dump if needed... All that I understood is - LRUMapTileCache doing useless job in offline mode or something like, but idk how to fix it :/


text:
Q: GNU Radio audio underrun on FM Radio Capture, using the hackrf compatible rad1o badge from CCC I'm being unable to finish the 1st lesson of http://greatscottgadgets.com/sdr/1/ successfully. The example runs, but instead of being able to capture the tuned radio station, I only get noise. GNU Radio companion keeps printing audio underrun erros.
I'm using GNURadio on a Kali VM on a Mac OS X i7 with 16Gb

A:
GNU Radio companion keeps printing audio underrun erros.

Underrun means that your audio device is not getting the samples per seconds it needs. Maybe it doesn't support the sampling rate you configured it to, maybe your VM is just running too slowly (audio emulation in VMs is especially problematic).
You should try using GNU Radio natively. GNU Radio has a live image that you can put a DVD or USB stick and try out natively.
Also, try different audio sampling rates in the audio sink (you will need to adjust the audio rate/decimation in the demodulator, too!). 44100 works best, typically.

A: I was able to find success with this by setting the Audio Sink to 36kHz. Good luck

A: This may be caused by Pulse Audio, see the wiki.
Please try modifying the ~/.gnuradio/config.conf to:
[audio_alsa]
nperiods = 32
period_time = 0.010
verbose = false

*

*Open the file in a text editor:
nano ~/.gnuradio/config.conf

*identify the [audio_alsa] section.

*Check the values match the text above.
This should resolve the bitty audio, but the complete lack of radio could mean your signal isn't strong enough or you're on the wrong frequency. Try moving the SDR aerial around, preferably near a window to get a better signal.
For finding radio stations, it might help to replace Scott's channel_freq variable with a slider from GUI Widgets > QT > QT GUI Range. This gives you a slider that will control the frequency, some suggested values but I don't know the full FM range:
Id: channel_freq
Label: Channel Frequency
Type: "float"
Default Value: 100e6
Start: 70e6
Stop: 120e6
Step: 1e3
Wisget "Counter + Slider"
Minimum Length: 200

For anyone else following Scott's guide in 2021, some of the features he's using have been deprecated, such as the WX GUIs, there are replacements for these under QT instead, in particular the "WX GUI FFT Sink" can be replaced with the "QT GUI Sink".


text:
Q: How to sort order items in Order PDF template I'm trying to sort order's items according to a custom product attribute (localisation) in Order Print PDF,
I tried this in vendor/magento/module-sales/Model/Order/Pdf/Invoice.php
 public function getPdf($invoices = [])
 {

    $this->_beforeGetPdf();
    $this->_initRenderer('invoice');

    $pdf = new \Zend_Pdf();
    $this->_setPdf($pdf);
    $style = new \Zend_Pdf_Style();
    $this->_setFontBold($style, 10);

    foreach ($invoices as $invoice) {
        if ($invoice->getStoreId()) {
            $this->_localeResolver->emulate($invoice->getStoreId());
            $this->_storeManager->setCurrentStore($invoice->getStoreId());
        }
        $page = $this->newPage();
        $order = $invoice->getOrder();
        /* Add image */
        $this->insertLogo($page, $invoice->getStore());
        /* Add address */
        $this->insertAddress($page, $invoice->getStore());
        /* Add head */
        $this->insertOrder(
            $page,
            $order,
            $this->_scopeConfig->isSetFlag(
                self::XML_PATH_SALES_PDF_INVOICE_PUT_ORDER_ID,
                \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
                $order->getStoreId()
            )
        );
        /* Add document text and number */
        $this->insertDocumentNumber($page, __('Invoice # ') . $invoice->getIncrementId());
        /* Add table */
        $this->_drawHeader($page);
        /* Add body */
        foreach ($this->sortByLoc($invoice->getAllItems()) as $item) {
            if ($item->getOrderItem()->getParentItem()) {
                continue;
            }
            /* Draw item */
            $this->_drawItem($item, $page, $order);
            $page = end($pdf->pages);
        }
        /* Add totals */
        $this->insertTotals($page, $invoice);
        if ($invoice->getStoreId()) {
            $this->_localeResolver->revert();
        }
    }
    $this->_afterGetPdf();
    return $pdf;
}

public function sortByLoc($items) {
    $AllItems = [];

    foreach ($items as $tempItem) {
        if($tempItem->getProduct()){
            if($tempItem->getProduct()->getData('localisation'))
                $AllItems[$tempItem->getProduct()->getData('localisation')][$tempItem->getName()] = $tempItem;
            else
                $AllItems[][$tempItem->getName()] = $tempItem;

        }
        else
            $AllItems[][$tempItem->getName()] = $tempItem;
    }

    $returnItems = [];
    ksort($AllItems);
    foreach ($AllItems as $tempItem) {
        foreach ($tempItem as $it) {
            $returnItems[] = $it;
        }
    }

    return $returnItems;
}

But this sort items in the invoice PDF not the Order Print PDF. I didn't find the order items that are displayed in the Order PDF.


text:
Q: How to configure Nginx with React Router HistoryLocation? I'm currently using Nginx as a reverse proxy and to serve my static assets. I was using React Router's HashLocation setting since it was the default and it allowed me to refresh on a route with no problems and no need for any additional configurations, but the issue with using that setting is the necessity of the url having /#/ prepending my routes (e.g. http://example-app.com/#/signup).
I'm now trying to switch to React Router's HistoryLocation setting, but I can't figure out how to properly configure Nginx to serve index.html for all routes (e.g. http://example-app.com/signup).
Here's my initial nginx setup (not including my mime.types file):
nginx.conf
# The maximum number of connections for Nginx is calculated by:
# max_clients = worker_processes * worker_connections
worker_processes auto;

# Process needs to run in foreground within container
daemon off;

events {
  worker_connections 1024;
}

http {
  # Hide nginx version information.
  server_tokens off;

  # Define the MIME types for files.
  include       /etc/nginx/mime.types;

  # Update charset_types due to updated mime.types
  charset_types
    text/xml
    text/plain
    text/vnd.wap.wml
    application/x-javascript
    application/rss+xml
    text/css
    application/javascript
    application/json;

  # Speed up file transfers by using sendfile() to copy directly
  # between descriptors rather than using read()/write().
  sendfile      on;

  # Define upstream servers
  upstream node-app {
    ip_hash;
    server 192.168.59.103:8000;
  }

  include sites-enabled/*;
}

default
server {
  listen  80;
  root    /var/www/dist;
  index   index.html index.htm;

  location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
    expires 1d;
  }

  location @proxy {
    proxy_set_header    Upgrade $http_upgrade;
    proxy_set_header    Connection "upgrade";
    proxy_set_header    Host $host;
    proxy_set_header    X-Real-IP $remote_addr;
    proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header    X-NginX-Proxy true;

    proxy_http_version  1.1;
    proxy_redirect      off;
    proxy_pass          http://node-app;
    proxy_cache_bypass  $http_upgrade;
  }

  location / {
    try_files $uri $uri/ @proxy;
  }

}

This setup worked fine when I was using HashLocation, but after changing to HistoryLocation (the only change I made), I get back a 404 Cannot GET when attempting to refresh on a sub-route's url.
if (!-e $request_filename){
  rewrite ^(.*)$ /index.html break;
}

in the location / block. This allows me to refresh and directly access the routes as top locations, but now I can't submit PUT/POST requests, instead getting back a 405 method not allowed. I can see the requests are not being handled properly as the configuration I added now rewrites all my requests to /index.html, and that's where my API is receiving all the requests, but I don't know how to accomplish both being able to submit my PUT/POST requests to the right resource, as well as being able to refresh and access my routes.

A: location / {
    try_files $uri /your/index.html;
}

http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files
I know your example is more complex with the @proxy but the above works fine for my application.


text:
Q: How can I monitor a wi-fi device communication like monitoring an Ethernet-linked device using port-mirroring switch and WireShark? In an Ethernet network, it's well-known to connect devices with a port-mirroring switch and then watch communication among devices using WireShark. Before WireShark can capture packets from other ports, port mirroring must be set first.
But, is there similar methods to monitor the communication of a device that connects to the same wi-fi AP with the monitoring computer which runs WireShark?

A: Connect the AP to an Ethernet switch with port-mirroring, then use the existing procedure. (If you need to monitor traffic between two Wi-Fi devices, connect them to separate SSIDs on two different APs, with Ethernet in between.)
If the AP provides SSH access, it might have a packet capture feature built in (e.g. UniFi firmwares run Linux and include tcpdump which can be streamed via SSH; RouterOS devices have /tool/packet-sniffer which supports UDP streaming).


text:
Q: Exception occurs in Windows .Net Application because of version mismatch on DLL I have a Windows Service application that I can also run as a Windows Form application for testing purposes. There are several dlls that are linked to my main project. Only one is causing me a problem. The inner exception gives me a clue that something is wrong. Here it is:

{"Could not load file or assembly 'HIDDProcessing, Version=1.0.5191.17319, Culture=neutral, PublicKeyToken=863435ae869eb242' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)":"HIDDProcessing, Version=1.0.5191.17319, Culture=neutral, PublicKeyToken=863435ae869eb242"}
System.IO.FileLoadException: {"Could not load file or assembly 'HIDDProcessing, Version=1.0.5191.17319, Culture=neutral, PublicKeyToken=863435ae869eb242' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)":"HIDDProcessing, Version=1.0.5191.17319, Culture=neutral, PublicKeyToken=863435ae869eb242"}

I can solve this by deleting the hiddprocessing.dll's and recompiling. However I'm wondering why I have to do this. None of the other dll's are causing me any problems.
I have noticed that if I do to the reference list all the other dll have a fixed version number. For example 1.0.0.0. While my problem dll has a specific version, for example 1.0.5190.26584. If I could get rid of the specific version, I think my problem would go away. But I don't know how to do it.


text:
Q: How Can I Keep the Code Running when the Window Closed? (PYQT5) I'm working on a basic project with using PyQt5. I made a break method so I can close app with pressing a button. I made a loop in this but when I close the window loop doesn't go back. I want to able to close the window without quitting the program fully.
There is 'main' side:
        if __name__ == "__main__":
        app = QtWidgets.QApplication(sys.argv)
        mainWin = TextBar()
        mainWin.show()
        sys.exit(app.exec_())

And there is button and its command:
pybutton = QPushButton('OK', self)
            pybutton.clicked.connect(self.clickMethod)
            pybutton.resize(200, 32)
            pybutton.move(80, 100)

        def clickMethod(self):
            print('Name: ' + self.tool.text(), '\nProperties:' + self.prop.text(), '\n')
            TextBar.close(self)

I want to close ONLY window when I press OK, NOT full of program.

A: when the Mainwindow is closed nothing should be running, unless you consider hidding it, like
YourQMainWindow.hide()
self.YourQMainWindow.hide()

2-Methode initialize 2 difference instances, like that once one is closed, another remains or, at about to close, your run a second instance
if __name__ == "__main__":
    app = Qtw.QApplication(sys.argv)
    main_window = MainWindow()   #---->first instance
    main_window1 = MainWindow()  #---->second instance
    sys.exit(app.exec())

if you run then both, they take more ressouces,
so i suggest you create a button to close the first one, that alse start at the same time the second instance of your app,....
Unless you provide more reproductible example (a piece of code), this is how i can only go in advicing you,...(please confirm if it's working for you, me i always use this technic, & it's working),...thank you


text:
Q: Java performance - good practices (using references) This is the basic structure of code on a project I am contributing to:
protected ModelAndView showForm(ActionContext ctx) throws Exception {
    Command cmd = ctx.getCommand();
    SubCommand subCmd = cmd.getSubCommand();
    doSmth(cmd, subCmd);
    doSmthElse(ctx);
    doSmthElse2(ctx);
}

and every doSmthElse(ctx) begins with
Command cmd = ctx.getCommand();
SubCommand subCmd = cmd.getSubCommand();

for me it is NOT clear why it looks like this and it should be changed towards the way it looks in doSmth. Please correct me if i'm wrong, but i think it also works slower as it is now.

A: If getCommand is as simple as return command; then there won't be any performance difference.
From a design perspective, if doSmthElse only needs the sub command to do its work, then you could indeed pass what it needs and only what it needs rather than a "generic" context object that contains unnecessary information - it will allow easier testing too. If that is the case, it would make sense to call doSmthElse(subCmd).
But that will mean that if you need more information at a later stage you will need to change the method signature.
In other words, as often, it depends...

A: I would say that the major point is not performance per se, but it's a conceptual/clarity thing. If the commands and subcommands always go together, then it makes more sense to replace doSmth(cmd, subCmd) with doSmth(ctx).
Regarding performance, if the object is prebuilt (that is, it doesn't get rebuilt on a getter call), it does not matter how many references to it there are.


text:
Q: How to style the container of a jQuery Select2 combo box? Is it possible to style the combo box container using the Select2 jQuery plugin? I can successfully style the dropdown menu where autocomplete selections appear, but not the container where text is entered. Here's what I'm doing:
$(document).ready(function() {
    $("#combo").select2({
        data:[{id:0,text:'One'},{id:1,text:'Two'}],
        multiple: true,
        createSearchChoice: function (term) {
            return { id: term, text: term };
        },
        containerCss: 'container',
        dropdownCssClass: 'dropdown',
        containerCss: {
            background: 'green'
        }
    });
});

<input type="hidden" id="combo" style="width:350px" />

#combo {
    background: green;
}
.container {
    background: green;
}
.dropdown {
    background: red;
}

The container should be green, but it's not. Here's a fiddle.
Edit:
I noticed on the documentation page for the site (which is quite comprehensive) that every example of the kind I'm trying to do (hidden input field with dynamically loaded options) has the same standard style, like in my example fiddle. The version that originates from a select element, however, has rounded corners etc. If this means you can't style the container when using a hidden input, it's seems like an odd limitation.
Edit2:
@emmanuel has already provided a solution, but since I was actually after the border-radius, there was a bit more to do to get it working properly. After setting the radius on all corners, opening the dropdown results in rounded corners visible between the top of the dropdown and the bottom of the container, which is a bit ugly. You can do something like this to fix it:
$('ul.select2-choices').on("select2-open", function() {
    $('ul.select2-choices').css({
        'border-bottom-left-radius': '0px',
        'border-bottom-right-radius': '0px',
    });
});
$('ul.select2-choices').on("select2-close", function() {
    $('ul.select2-choices').css({
        'border-bottom-left-radius': '5px', // or whatever
        'border-bottom-right-radius': '5px', // or whatever
    });
});

I think this will cause a problem, though, for any other Select2 combo boxes visible on the same page.

A: In order to add background color to container you have to put the rule to #s2id_combo. The problem is that ul.select2-choices already has a background and it's over container so you have to add:
ul.select2-choices { background: green !important; }


text:
Q: Lights and shadows in Unity So, I'm making a game with Unity, and I have to cover other parts of the level with a shadow, so that the player can't see them. This is how the game looks like now, and more or less i'd like it to look like this
Someone nows how to help me? Like with some tutorials or tips.
Thank you so much.

A: One solution it would be to cover the part of the level with an object, and you may remove it by using a collider to detect if player is near or maybe by player position


text:
Q: SQL count of values from different columns I've got a Dog table. Each dog has Breed and can have 0 to 2 photos. I need to recieve count of photos of all dogs for each breed: table with BreedId and matching PhotosCount. So result table should be:
BreedID|PhotosCount
-------------------
1      |3
-------------------
2      |1
-------------------

A: This should do the trick:
SELECT BreedID AS B, COUNT(Photo1) + COUNT(Photo2) AS C
FROM Dog
GROUP BY BreedID

COUNT aggregate function simply doesn't take into consideration NULL values. If, for a specific BreedID, all values of either Photo1 or Photo2 are NULL, then COUNT returns 0.

A: This should work in single scan:
SELECT
    BreedID,
    SUM(CASE WHEN Photo1 IS NOT NULL THEN 1 ELSE 0 END)
    + SUM(CASE WHEN Photo2 IS NOT NULL THEN 1 ELSE 0 END) [Count]
FROM Table
GROUP BY BreedID

A: Use Group By and SUM Of Photo1 and Photo2:
Note: If you wants the output for each dog you have to include DogId in group clause.
;WITH T AS
(
    SELECT
        BreedId,
        SUM (CASE ISNULL(Photo1,0) WHEN 1 THEN 1 ELSE 0 END) AS Photo1,
        SUM (CASE ISNULL(Photo2,0) WHEN 1 THEN 1 ELSE 0 END) AS Photo2
    FROM TableName
    Group By BreedId
)
SELECT
    BreedId,
    SUM(Photo1+Photo2) AS TotalPhoto
FROM T

Or Simply
SELECT
    BreedId,
    SUM (CASE ISNULL(Photo1,0) WHEN 1 THEN 1 ELSE 0 END +  CASE ISNULL(Photo2,0) WHEN 1 THEN 1 ELSE 0 END) AS TotalPhoto
FROM TableName
Group By BreedId

A: SELECT BreedID AS Breed, COUNT(Photo1) + COUNT(Photo2) AS #ofPhotos
FROM Dog
GROUP BY BreedID;