text:
Q: How to target class within html table via media query? I'm seriously stumped on this one. I'm attempting to use one of Dan Mall's recommended techniques for setting line breaks, but on mobile in an html email signature, just as a progressive enhancement where media queries are supported. I'm doing this within a table cell, but I'm trying to do it in text, via a span or a br tag with a class, instead of applying media queries to a tr or td. However, even when testing in Chrome, the media queries don't seem to be applying at all. For my media queries, I'm doing:
@media screen and (max-device-width:480px) {
  span[class="rwd_hidden"] { display:visible !important; }
  br[class="rwd_break"] { display: none !important; }
}

@media screen and (min-device-width:481px) {
  span[class="rwd_hidden"] { display:hidden !important; }
  br[class="rwd_break"] { display: hidden !important; }
}

and the applicable section from my HTML:
Office
(000) 000-0000

|

Just trying bracket class targeting here because I read Yahoo sometimes stumbles over that—I've done it both ways. Mainly just trying to break a long line with two phone numbers, only on mobile, and to hide the pipe divider, but no luck. Any help? Is it normally not possible target things with a MQ within a table?

A: Your media queries are fine. It's just that "visible" isn't an acceptable option for the display: property – I think you might have display confused with visibility.
I think Dan Mall's original approach should be fine here. It looks like you're also using .rwd_hidden, so I've added that to his code.
@media screen and (min-device-width:481px) {
  .rwd_hidden,
  .rwd_break {
      display:none;
  }
}


text:
Q: Activity objects persisting in memory even after calling finish and making the references null I am making a retrofit enqueue call from SplashActivity and passing data to next activity via bundles.Even after explicitly calling finish on splash activity it still has 48 references in retained heap as seen in MAT.
The app in general is also taking a lot of memory in the background. I debugged and found that my activity's onDestroy() method is getting called, but why are the objects still persistent in the memory? Is it somehow related to the data being passed by reference instead of value? I've been trying to search around the web but with hardly any luck. Please point me if I'm looking in the wrong direction here.
Here's a snapshot of my Splash Activity-
public class SplashActivity extends AppCompatActivity {

private String TAG = SplashActivity.class.getSimpleName();

List<Sport> mSportsList;
List<Event> mEventsList;
List<Carousel> mCarouselList;
WatchOnApiService mWatchOnApiService;

@BindString(R.string.package_name)
String mPackageName;

ProgressBar mProgressBar;
AlertDialog.Builder alertDialogBuilder;
AlertDialog alertDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);
    ButterKnife.bind(this);
    MobileAds.initialize(getApplicationContext(), "ca-app-pub-8433136449848959~7585529227");

    mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    mProgressBar.getIndeterminateDrawable().setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY);
}

@Override
protected void onResume() {
    super.onResume();
    getSportsAndEventsAndCarousel();
}

private void getSportsAndEventsAndCarousel() {
    mProgressBar.setVisibility(View.VISIBLE);

    WatchOnApiService mWatchOnApiService = RetrofitFactory.getRetrofit().create(WatchOnApiService.class);
    final Call<WatchOnSportsEventsCarousel> mCall = mWatchOnApiService.getAllSportsAndEventsAndCarousel(TimeZone.getDefault().getID());

    mCall.enqueue(new Callback<WatchOnSportsEventsCarousel>() {
        @Override
        public void onResponse(final Response<WatchOnSportsEventsCarousel> response, Retrofit retrofit)
        {
            if (response.isSuccess()) {

                mProgressBar.setVisibility(View.INVISIBLE);

                if (Float.parseFloat(BuildConfig.VERSION_NAME) < Float.parseFloat(response.body().getAndroidLatestVersion())) {
                    if (response.body().getAndroidForceUpdate().equalsIgnoreCase("1")) {

                        showForceUpdateDialog();

                    } else {
                        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(SplashActivity.this);
                        alertDialogBuilder.setTitle("WatchOn");
                        alertDialogBuilder.setMessage("WatchOn just got better.Would you like to upgrade ?");
                        alertDialogBuilder.setPositiveButton("Upgrade",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int arg1) {
                                        dialog.dismiss();

                                        try {                                                SplashActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + mPackageName)));
                                        } catch (android.content.ActivityNotFoundException anfe) {
                                            SplashActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + mPackageName)));
                                        }
                                    }
                                });
                        alertDialogBuilder.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                beginFlow(response);

                            }
                        });

                        AlertDialog alertDialog = alertDialogBuilder.create();
                        alertDialog.show();
                    }
                } else {
                    beginFlow(response);
                }
            }

            //Response not received something went wrong
            else {
                showAlertDialogNoResponse();
            }
        }

        private void beginFlow(final Response<WatchOnSportsEventsCarousel> response) {

            Bundle mBundle = new Bundle();

            mSportsList = CodeUtils.convertSportsListToLocalTime(response.body().getData().getSports());
            Parcelable wrappedSports = Parcels.wrap(new ArrayList<>(mSportsList));
            mBundle.putParcelable(AppConstants.SPORTS_LIST, wrappedSports);
            mEventsList = CodeUtils.convertEventsListToLocalTime(response.body().getData().getEvents());
            Parcelable wrappedEvents = Parcels.wrap(new ArrayList<>(mEventsList));
            mBundle.putParcelable(AppConstants.EVENTS_LIST, wrappedEvents);
            mCarouselList = response.body().getData().getCarousels();
            Parcelable wrappedCarousels = Parcels.wrap(new ArrayList<>(mCarouselList));
            mBundle.putParcelable(AppConstants.CAROUSELS_LIST, wrappedCarousels);

            if ((response.body().getLiveSponsors() == 1)) {
                mBundle.putBoolean(AppConstants.LIVE_SPONSORS_AVAILABLE, true);
            } else {
                mBundle.putBoolean(AppConstants.LIVE_SPONSORS_AVAILABLE, false);
            }

            Intent i = new Intent(SplashActivity.this, SelectSportEventActivity.class);
            i.putExtras(mBundle);
            mSportsList = null;
            mEventsList = null;
            mCarouselList = null;
            startActivity(i);
            SplashActivity.this.finish();
        }

        @Override
        public void onFailure(Throwable t) {
            showAlertDialogInternetFail();
            alertDialogBuilder.setNegativeButton("Retry", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    getSportsAndEventsAndCarousel();
                    dialog.dismiss();
                }
            });
            alertDialog = alertDialogBuilder.create();
            alertDialog.show();

        }
    });
}

@Override
protected void onDestroy() {
    ButterKnife.unbind(this);
    Log.d(TAG, "onDestroy: " + mSportsList + mEventsList + mCarouselList);
    alertDialog = null;
    super.onDestroy();
}

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ember application loads blank page in IE11 I have started my ember application in local and if it launched in chrome it works fine but when i give the URL in IE 11 a blank page is loading ...pls let me know how to fix it

A:
multiple definitions of a property not allowed in strict mode

To resolve this error, you need to remove duplicated function/property name which is mentioned in console. At any point of time you should have only one function/property with the same name.
for examle say,
export default Component.extend({
    foo: function(){
        //foo function
    },
    foo: function(){
        //this will produce error in IE strict mode and it will not execute JS
    }
});


text:
Q: STM32f103 HAL USB - UART bridge I have a third party device that is UART programmable.
I need to create a USB - UART bridge with a functional password (programming only after entering the correct password)
generated the code using the latest version of STM32CubeMX for Atollic TrueSTUDIO for STM32 9.3.0 ...
I transfer data between USB and UART through a buffer (one for usb-uart, and another one for uart-usb)
when I try to transfer several characters everything is OK, but when I try to transfer a large data packet, problems start due to the fact that the USB speed is much higher than the UART ...
there are two questions:
1.How do I tell USB that I need to stop transferring data and wait until the UART (buffer) is busy
2.How on the side of the microcontroller to get the baud rate set on the PC (set when the terminal is connected to the virtual COM port)

A: USB provides flow control. That's what you need to implement. A general introduction can be found here:
https://medium.com/@manuel.bl/usb-for-microcontrollers-part-4-handling-large-amounts-of-data-f577565c4c7d
Basically, the setup for the USB-to-UART direction should be:

*

*Indicate that the code is ready to receive a USB packet

*Receive a USB packet

*Indicate that you are no longer ready to receive a USB packet

*Transmit the data via UART

*Start over

Step 0: Initial setup
Call USBD_CDC_SetRxBuffer to set the buffer for receiving the USB data. Unless you use several buffers to achieve higher throughput, a single call at the start of the program is sufficient.
Step 1: Ready to receive data
Call USBD_CDC_ReceivePacket. Other than what the name implies, this function indicates that the app is ready to receive data. It immediately returns before the data has actually been received.
Step 2: Receive a USB packet
You don't need to do anything here. It will happen automatically. Once it's complete, CDC_Itf_Receive will be called.
Step 3: Indicate that you are no longer ready to receive a USB packet
Nothing to do here. This happens automatically whenever a packet has been received (and double buffering is not enabled).
Step 4: Transmit the data via UART
I guess you know how to do this. It's up to you whether you want to do it in a blocking fashion or using DMA.
Since a callback is involved, you cannot put this code into the main loop. It might be possible to put all code into CDC_Itf_Receive if blocking UART is used. It would appear in the order 2, 3, 4, 1. Additionally, initialization is needed (0 and 1).
In the UART-to-USB direction, you would need to implement flow control on the UART. The USB flow control is managed by the host. Even though USB is much faster than UART, flow control is relevant as the application on the host can process data as slow as it likes to.
Regarding question 2: I'm not sure I understand it... The microcontroller cannot set the baud rate on the host. Either the host can specify a baud rate (transmitted over USB and applied to UART), or if the UART has a fixed baud rate, you can ignore baud rate (any baud rate set on the host side will work as it does not apply to USB).


text:
Q: Authentication using React I'm working on a project using React in the front-end and Django in the back-end.
I Used the useState function in React to handle the isConnected variable.
my problem right now is that the isConnected takes the initial value whenever I refresh my webpage, which is false, this is my code :

const [isConnected, setIsConnected] = useState(false)

useEffect( async () => {

    async function checkJWTValidity(){
      try{
        axios.defaults.headers.post['Authorization'] = "JWT "+localStorage.getItem("token")

        //fetching ME data from API
        const requestdata = await axios.post(
          utils.endpoint,{query: utils.meQuery}
        )

        //checking if the returned Data is NULL, if so, tokens would be deleted from localStorage.
        //else token variables will remain for its still valid.
        if(requestdata.data.data.me === null){
          const tokenItems = await getNewJWT(localStorage.getItem("refreshToken"))
          if(tokenItems.length === 0){
            localStorage.removeItem("token")
            localStorage.removeItem("refreshToken")
            setIsConnected(false)
            console.log("null")
          }
          else{
            localStorage.setItem("token", tokenItems[0])
            localStorage.setItem("refreshToken",  tokenItems[1])
            setIsConnected(true)
          }
        }
        else{
          console.log(isConnected)
          setIsConnected(true)
        }
      }
      catch(err){
          console.log(err)
      }
    }

    async function getNewJWT(refreshToken){
      const token = []
      try{
        //fetching refreshToken data from API
        const requestdata = await axios.post(
          utils.endpoint,
          {
            query: utils.refreshQuery(refreshToken)
          }
        )

        //checking if the returned Data is NULL, if so, tokens would be deleted from localStorage.
        //else token variables will remain for its still valid.

        if(requestdata.data.data.refreshToken.errors === null){
          token.push(requestdata.data.data.refreshToken.token.toString())
          token.push(requestdata.data.data.refreshToken.refreshToken.toString())
        }

      }
      catch(err){
          console.log(err)
      }
      return token
    }

    checkJWTValidity();
  }, [])

if there are any optimal solutions that I could do, please tell me!
Thanks

A: Whenever refreshing the browser webpage, your component tree and state will reset to the initial state.
To keep a previous state after a page reload in the browser, you need to do any one of the following

*

*Save state locally in localStorage or IndexedDB

*or At the server-side to reload.

And you need to add code at initialization to check previously saved local state or server-state, In this way, you can restore your previous state.

A: If you have sub components that are reliant on the validity of the token you can block further rendering while isConnected is false. This way you give the token time to refresh or be confirmed.
const Auth = ({children}) => {
    const [isConnected, setIsConnected] = useState(false);

    useEffect(async () => {
        if (!isConnected) {
            async function checkJWTValidity() {
                // ...
            }
        }
    }, [isConnected]);

    return isConnected ? children : null;
};

I've also added the isConnected value to the dependencies array and put an if statement inside the useEffect.
There will always be a point in time where the default state is used, however short amount of time it might be. This is the nature of javascript and web apps.


text:
Q: media query iPad in landscape mode and above My CSS looks like this:
/* width 1024px up to 1600px */
/* main CSS */

/* width 1601px up to 1920px */
@media screen and (min-width: 1601px) {
/* CSS */
}

/* wider than 1920px */
@media screen and (min-width: 1921px) {
/* CSS */
}

/* mobile */
@media only screen and (max-width: 1023px) {
/* CSS */
}

Everything works as expected except the iPad in landscape mode which shows the mobile version although the mobile version only targets devices up to 1023px. I want the iPad to show the main css.


text:
Q: Using existing liferay login for android I'm modifying a native Java Android app that shows in the phone a liferay website.
The former login was done on a salesforce website, i can reach the user login to mantain the session with the sid cookie...
CookieManager cookieManager = CookieManager.getInstance();
String cookies = cookieManager.getCookie(url);
// get the cookie containing "sid="

Then, when adquired the cookie I know I can redirect to the web without problem and I can mantain the login.
Now, customer wants to change this login and use the existing app's liferay login. I can acceed to liferay website and login but it's not redirecting anywhere, just going to user's profile...
There is a way to catch the success login and then redirect to a private website?
I've tried to import some liferay libraries to create a session as in tutorials:
Session session = SettingsUtil.getSession();

But I think is not really what I need, cause i don't need a liferay app, just check for success login and redirect to website...

A: Liferay Community
Liferay quite smart with this, you only need to load the private home URL, so Liferay will catch the request, keep it, redirect you to login page and when succeed go to original private url mantaining the user login active.
webView.loadUrl("/url/to/home");

Liferay Enterprise
If you try to do it in same way login is not valid and behaviour becomes weird (acting different by devices, emulators and android versions).
After many tests (I hate debugging webviews :@), we've found a workaround: instead of load home url direct, you must include login url and include ?redirect= in the webView load:
webView.loadUrl("/url/to/login?redirect=/url/to/home");


text:
Q: SQL split column value (if column value has more than 5 characters) into multiple rows I have a table:
Name    | Number
Lisa    | P1234P6953
Monica  | P0034
Hayley  | P0021P5691

I want to achieve the below result. Can someone please help with this? When number column has more than 5 characters, after fifth character it should be splitted into multiple rows.
Name    | Number
Lisa    | P1234
Lisa    | P6953
Monica  | P0034
Hayley  | P0021
Hayley  | P5691

A: -- SQL Server, but fairly adaptable to other platforms
with split as (select 1 as ofs union all select 6)
select Name, substring(Name, ofs, 5)
from T inner join split on ofs < len(Name)

Other platforms might have slightly better options. I'm assuming that you have a substring() function of some kind and as well as len(). For convenience I assumed that you can use a CTE. Generally I would discourage you from saving data in this format as it is not the preferred way to use a SQL database.


text:
Q: Provided address undefined is invalid, the capitalization checksum test failed, or it's an indirect IBAN address which can't be converted When I use
 web3.fromWei(web3.eth.getBalance(web3.eth.accounts[0]), "ether").toNumber()

it should get the balance of accounts[0] which is the coinbase
but what I get is

"Provided address undefined is invalid, the capitalization checksum
test failed, or it's an indirect IBAN address which can't be
converted."

Is there any way I can figure this out?
Truffle v5.4.13
Solidity v0.5.16
Web3.js v1.5.3
these are the version im using

A: This means that web3.eth.accounts[0] is undefined. You can use
console.log(web3.eth.accounts)

to check those or if you're feeling adventurous you can learn how to use the debugger to inspect things.


text:
Q: What ":" means in the tree view of android project dependencies? When I view the tree view of my android project's dependencies, I see the following entry:
+--- androidx.legacy:legacy-support-v4:1.0.0
|    +--- androidx.core:core:1.0.0 -> 1.7.0-alpha01
|    |    +--- androidx.annotation:annotation:1.2.0

If I understand correctly, this means that "androidx.legacy:legacy-support" contains a dependency on "androidx.core:core", and so on
There are also other entries in this tree like
+--- org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.70 -> 1.4.30 (*)
+--- :mopub-chartboost-adapters-8.2.0.3

Please advice what does ":" symbol before "mopub-chartboost-adapters" mean? Does "org.jetbrains.kotlin:kotlin-stdlib" contains dependency on "mopub-chartboost-adapters"?
Thanks

A: I assume this is a local dependency. Check if you have placed an aar for mopub-chartboost-adapters-8.2.0.3 in a local folder which is consumed by gradle in the dependencies section of the build.gradle file.
org.jetbrains.kotlin:kotlin-stdlib" does not contain a dependency on "mopub-chartboost-adapters": pom.xml


text:
Q: Sony Playstation 3 PS3 Won't see Media Server I'm kind of lost, not really sure what to do so if anyone can input me on this I'd highly appreciate it. (I'm getting to the point where I'm about to do something stupid).
I recently purchased a new TV, not that it would make any difference but the model is: KDL-55HX800. That TV supports natively DLNA, so I thought I'd take advantage of that.
prior to using that TV, I was using my old TV w/ XBOX360 hooked up through Apple Airport Express where over WiFi I'd get a signal form my Apple Airport Extreme and over ethernet it'd go to my XBOX360, on my desktop I use Yazsoft Playback software that was working without any problems at all.
so here is what I change, since TV has a way to connect ethernet cable I did that and I moved in my PS3 to same room, so to connect all that I took non-managed small switch and now networking wise everything works, I'm able to obtain IP address for TV, XBOX and PS3 and I'm able to ping from my Desktop all of these devices, yet neither of these devices are able to see my Desktop's DLNA server.
I also used my Motorolla Droid X phone, enabled DLNA server there and all devices now are able to see my new DLNA server, so that makes me think that it's all my Desktop's fault, yet over there I turned off LittleSnitch, Native OSX firewall and through netstat I can see that server is started and able to serve content.
Any ideas?

A: This helped: .local - Wikipedia, the free encyclopedia .


text:
Q: How to get the image as background using url, with PHP, GD? I am trying to get image from one IP camera, which has url like http://publicip:1234/mypicture.jpeg
But how do i attache that image to this as background?
  $im = imagecreatefromjpeg('http://publicip/video/meandmyCPU.jpeg');
  //$black = imagecolorallocate($im,255,0,0);
  //              s   x  y
  Imagestring($im,19,70,70,'MY NAME IS!',$black);
  header('Content-type: image/png');
  imagejpeg($im);
  imagedestroy($im);

But it does not show my texts.

A: Are you explicitly loading a font using imageloadfont?   I don't think 19 is a valid font identifier, unless you loaded it yourself, and given the docs on imageloadfont, I don't think 19 would be a valid identifier either.
http://php.net/manual/en/function.imagestring.php
If so, check that the load succeed, you don't have errors, etc.  Assuming it's the text not displaying (your question is somewhat unclear in that it asks about attaching a background, and also says the text doesn't appear, which implies that the image does)
If the background isn't appearing, check that you can actually open a URL over HTTP - the default config on my webhost disables it as it's a security risk (as one could use it to read in arbitrary data and possible execute it, if for instance, if there's a security hole).


text:
Q: Where to store the downloaded .jar files? As I am new to Java, I want to ask that where should I put the downloaded .jar files, so that I don't have to use -cp option in javac command to compile it?
For example, suppose I have written a java code "HelloWorld.java" to do a basic input output and I have done import java.io.*; or import java.util.*;, and doing javac HelloWorld.java compile command on it works fine, however, if I have some (for example) import com.mongodb.BasicDBObject; line in my code and it won't compile without me downloading the mongo-java-driver-3.10.2.jar and putting it's location in -cp option of javac. (Like: javac -cp "/home/shivam/Downloads/*" HelloWorld.java).
So I just want to ask that where should I store the  mongo-java-driver-3.10.2.jar file in my computer so that, using just the javac NameOfCode.java command without the -cp option will compile my code successfully?
FYI, I have Ubuntu 18.04.2 and am using Java-11.
Thank you!!

A: You can put them in JAVA_HOME/lib, where JAVA_HOME is the path to your jdk setup


text:
Q: Pie Chart in Excel I tried to google this but no luck. It is easy to add a pie chart when you have prcentace data but what if you just have a list of partially repeated data?
For simplicity imagine there is a table in Excel which represents all cars in a town. One of columns is 'color'. How is it possible to add a pie chart representing colors of cars without calculating percentage? And, it is important to mention that if comeone will add a pink or any new color car first time into the table, the pie chart should automaticaly have one more slice.

A: If you have two columns:
Colour  Number
Red     3
Blue    5
Green   6
Purple  4
Black   10

Then create the pie from these it will work.
To add a new colour so it gets automatically inserted into the chart you'll need to insert a new line rather than just appending to the end.
Colour  Number
Red     3
Blue    5
Green   6
Purple  4
Pink    1     <-- new value inserted here.
Black   10


text:
Q: POST request to PHP does not retrieve any data when using a form instead of angular http client I am using angular http client to interact with database and everything works but when I am trying to POST data to the same link using a form, I get that the data is undefined.
I was trying to encode, decode values as I know that before making any POST request and sending data, I need to perform angular.toJSON method, but that did not work.
This is my index.php where I receive a POST request from the form.
if (empty($action)) {
    if ((($_SERVER['REQUEST_METHOD'] == 'POST')) &&
             (strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false)) {

        $input = json_decode(file_get_contents('php://input'), true);

        $action = isset($input['action']) ? $input['action'] : null;
        $subject = isset($input['subject']) ? $input['subject'] : null;
        $data = isset($input['data']) ? $input['data'] : null;
    }

case 'createNote':
        // if I die() here, it prints the die()
        if(!empty($data)) {
            // if I die() here, $data is undefined.
            $data = json_decode($data);

            $user = $data[0];
            $comment = $data[1];
            $film_id = $data[2];
            $lastupdated = date("Y-m-d H:i:s");

            $sql = "INSERT INTO nfc_note (user, film_id, comment, lastupdated)
                    VALUES (:user, :film_id, :comment, :lastupdated)";
        }
        break;

My form that I use to send POST request
<form action="index.php" method="POST">
    <input type="hidden" name="action" value="create">
    <input type="hidden" name="subject" value="note">
    <input type="hidden" name="data" value="<?php echo "['username','content', 1]"; ?>">

    <input type="submit" value="Submit">
</form>

As mentioned above, it works when I use angular's http and pass parameters like this:
this.createNote = function (data) {

    var defer = $q.defer(),
    data = {
        action: "create",
        subject: "note",
        data: angular.toJson(data)
    };
    $http
        .post(urlBase, data)
        .success(function (response) {
            defer.resolve({
                data: response.data
            });
        })
        .error(function (error) {
            defer.reject(error);
        });

    return defer.promise;
};

Does not work when I use a form. Any suggestions or mistakes that I am not aware of?

A: Your PHP code is expecting Json formatted data, and it is not getting that. It is because the HTML Form sends out POST data as application/x-www-form-urlencoded.
To support both data formats, you need to build a logic on your PHP code to detect either format. The data format is mentioned in the HTTP header where you can check that. Look for Content-Type. For POST data coming for your HTML form, it is application/x-www-form-urlencoded and for the Json it should be application/json.
You can read the form values in PHP by using $_POST[<form_parameter>]. In your case $_POST['data']. To make your HTML form a bit simpler you can also split the data array into their own inputs in the form.
See this for some more info: https://www.smtpeter.com/en/documentation/json-vs-post

A: I had the problem something like
"POST request to PHP does not retrieve any data when using a form instead of angular http client".
Normally use stream php to detect data from Angular to PHP
$data = file_get_contents('php://input');

But when scan the code with fortify it detect the xss vulnerability and I must change the methods.
Solved this problem in this way, I hope that help someone. :-)
ANGULAR:
$http({
method: 'POST',
url: '<?php echo base_url(); ?>admin/saveTemplateEmail',
headers: {'Content-Type': 'application/json'},
data: {templateEmail:$scope.selectedTipology}}).then(function (response) {.....}

PHP:
$data = file_get_contents('php://input');
$post_val = json_decode($data, true);

I changed it to the following
ANGULAR:
$http({
method: 'POST',
url: '<?php echo base_url(); ?>admin/saveTemplateEmail',
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
data: jQuery.param({templateEmail:$scope.selectedTipology})}).then(function (response) {.....}

PHP:
$post_val = $_POST;


text:
Q: C++ Program Not Reading Characters from File So, I'm trying to get the program to read a file and print out the number of sunny, cloudy and rainy days. It just keeps printing 0. What am I missing? I've tried to change the file from a .dat to .txt but still the same result. Here's what's in the data file:
RRCSSSCSCRRRCSSSCSSRSCCRCRRCSS
SSSCCSSSCCSSSCCSSSCRCRCCSSSSSS
SSSSCSSSCSSSCRRCCCSSSSSCSSSSCS
  #include <iostream>
    #include <fstream>
    #include <iomanip>
    #include <string>

    using namespace std;

    int main()

    {

    const int MONTH = 3;

    const int DAY = 30;

    char name[MONTH][DAY] = {"June", "July", "August"};
    char rain = 'R';
    char sun = 'S';
    char cloud = 'C';
    char letter;
    int day = 0;
    int count = 0;
    int rainy = 0;
    int cloudy = 0;
    int sunny = 0;

    ifstream inputFile;

    cout << " Weather for Summer Months\n";

    cout << "--------------------\n\n";

    inputFile.open("C:\rainorshine.dat");

    if (inputFile)
    {
    cout << "Error opening data file.\n";
        system("pause");
    }
    else

    {   cout << "Weather Report\n\n";

    while (inputFile >> letter)
    {
        cout << letter << endl;  // print out characters read from file
    }
   for (count = 0; count < MONTH; count++)
    {
        for (day = 0; day < DAY; day++)
        {
            cout  << name[count][day];
           inputFile >> name[count][day];
            if (name[count][day] == 'R')
                rainy++;
                else if (name[count][day] == 'S')
                sunny++;
            else if (name[count][day] == 'C')
                cloudy++;
        }

        cout << endl;
        cout << "  Sunny Days Total: " << rainy << endl;
        cout << "  Rainy Days Total: " << sunny << endl;
        cout << "  Cloudy Days Total: " << cloudy << endl << endl;
    }
    system("pause");
        return 0;
    inputFile.close();

    }
    }

A: This:
while (inputFile >> letter)
{
    cout << letter << endl;  // print out characters read from file
}

munches through all the letters, when it's done you're at the end of the file.
So when you try to read your data again in the for loop, there's nothing left to read.

A: "C:\rainorshine.dat"
// ^^

This isn't a backslash followed by a 'r', it's an escape sequence for carriage return character. You need to use forward slash or escape the backslash itself:
"C:/rainorshine.dat" or "C:\\rainorshine.dat"
Which means you never open the file. You would've noticed that if your condition were
if (!inputFile) // notice the !
{
    cout << "Error opening data file.\n";

instead of logically incorrect
if (inputFile) ...

A: After this line;
while (inputFile >> letter)
{
    cout << letter << endl;  // print out characters read from file
}

You need to reopen the file or seek back to the beginning. The next time you try to read the file you're already at the end so you get nothing.
Something like;
 inputFile.seekg(0, inputFile.beg);

should solve the problem.


text:
Q: Can't ping one server of two by name, but can ping both by IP I have two database servers where I can ping both by IP, but can only ping by name for one.
The setup:

*

*Server1 - Original Data

*Server2 - Receives data from Server1 through replication

Server1 can ping Server2 by IP and NAME.
Server2 can ping Server1 by IP but can't ping by NAME.
Why can't server2 ping server1 by name?
I need it because when I type the name of the database server, he doesn't recognize.

A: You have a name resolution problem. Based on what you've implied I'm assuming it's a DNS problem. Here are some steps to take:

*

*Identify your internal DNS server(s). Identify the appropriate DNS zone on the DNS server(s). Verifiy that the DNS zone is configured to allow dynamic updates. If this is an AD related zone you can allow secure updates only. If this is not an AD related zone then you need to allow both secure and unsecure updates.

*Make sure that both database servers are configured to use the DNS server(s) identified in step 1 for DNS name resolution.

*Make sure that both database servers are configured with a DNS suffix that matches your DNS zone. This will be the case if this is an AD domain and both database servers are joined to the domain.

*Verify that the correct A (host) records are registered in the DNS zone for both database servers. If they aren't registered or if they aren't correct, then delete the incorrect record and reregister it from the applicable server by running ipconfig/registerdns from a command prompt.

A: There are a lot of options here.  But here's where I'd start:

*

*What does nslookup server1 return?  If it's not the IP that you're looking for or returns empty, then that's your problem

*What about tracrt server1?  It might stop at some point, which would point you in the direction of where the problem is.

*Since we're talking about databases, have you tried to telnet to the port that sql server runs on on server 1 from server 2?  That's all that ultimately matters (the rest you can get around).

A: Try flushing dns resolver cache. If on Windows - start - run - ipconfig /flushdns from server2.

A: This sounds like a name resolution problem. Are both machines using the same DNS server, and are all of the names correctly registered?

A: Best practice is you add each server's IP and hostname to both server's hosts file.
For example, if your servers run Windows, then open up C:\Windows\System32\drivers\etc\hosts with Notepad and add:
192.168.1.101     dbserver1.domain.com
192.168.1.102     dbserver2.domain.com

to both servers (of course on your hosts file you will add your IPs and hostnames).


text:
Q: Rudin's proof of theorem 1.20b (Archimedean Principle) The theorem states:

(a) If $x\in \mathbb{R}, y\in \mathbb{R}$, and $x>0$, then there is a positive integer $n$ such that $$nx>y.$$
  (b) If $x\in \mathbb{R}, y\in \mathbb{R}$, and $x<y$, then there exists a $p\in Q$ such that $x<p<y$.
Since $x<y$, we have $y-x>0$, and (a) furnishes a positive integer $n$ such that $$n(y-x)>1.$$  Apply (a) again, to obtain positive integers $m_1$ and $m_2$ such that $m_1>nx$, $m_2>-nx$.  Then $$-m_2<nx<m_1.$$  Hence there is an integer $m$ (with $-m_2\leq m\leq m_1$) such that $$m-1\leq nx<m.$$

I am having a hard time understanding the reasoning behind the assertion "Hence there is an integer $m$ (with $-m_2\leq m\leq m_1$)" How is this inequality true? If $m$ = $-m_2$, then $-m_2>nx$ which is obviously a contradiction. I understand the finality of the proof is a result of the well ordering of integers. I just don't understand the justification of this particular inequality.

A: A non-empty subset of $\Bbb Z^+$ has a least member.
The set $S=\{j\in \Bbb Z^+: (j-m_2)-nx>0\} \,$ is not empty because $m_1+m_2\in S.$ So let $j_0=\min S$ and let $m=j_0-m_2.$
Now $m>nx$  because $m-nx=(j_0-m_2)-nx>0.$
We have $m_1+m_2\ge j_0.$ So $m_1\ge j_0-m_2=m.$
And $j_0-1\not \in S.$ So $(m-1)-nx=((j_0-1)-m_2)-nx\le 0.\;$ Hence $m-1\le nx.$
And $j_0\ge 0$ (because $j_0\in \Bbb Z^+$) so $m=j_0-m_2\ge 1-m_2>-m_2.$

A: $-m_2 < nx < m_1$, then $nx$ must be inside one of these interval $$[-m_2, -m_2+1), [-m_2+1, -m_2+2), \ldots, [m_1-2, m_1-1), [m_1-1, m_1)$$
so $m$ can take  one of the values from $-m_2+1$ up to $m_1$.

A: Note that $m_1,m_2$ are positive integers, so that in the interval $$[-m_2,m_1]$$ there will always be some integer -- at the very worst, the integer $0.$


text:
Q: A technical question about dynamic memory allocation in C I'm studying dynamic memory allocation in C, and I want to ask a question - let us suppose we have a program that receives a text input from the user. We don't know how long that text will be, it could be short, it could also be extremely long, so we know that we have to allocate memory to store the text in a buffer. In cases in which we receive a very long text, is there a way to find out whether we have enough memory space to allocate more memory to the text? Is there a way to have an indication that there is no memory space left?

A: You can use malloc() function if it returned NULL that means there no enough mem space but if it returned address of the mem it means there are mem space available example:
void* loc = malloc(sizeof(string));

A: ANSI C has no standard functions to get the size of available free RAM.
You may use platform-specific solutions.
C - Check currently available free RAM?

A: In C we typically use malloc, calloc and realloc for allocation of dynamic memory. As it has been pointed out in both answers and comments these functions return a NULL pointer in case of failure. So typical C code would be:
SomeType *p = malloc(size_required);
if (p == NULL)
{
    // ups... malloc failed... add error handling
}
else
{
    // great... p now points to allocated memory that we can use
}

I like to add that on (at least) Linux systems, the return value from malloc (and friends) is not really an out-of-memory indicator.
If the return value is NULL, we know the call failed and that we didn't get any memory that we can use.
But even if the return value is non-NULL, there is no guarantee that the memory really is available.
From https://man7.org/linux/man-pages/man3/free.3.html :

By default, Linux follows an optimistic memory allocation
strategy.  This means that when malloc() returns non-NULL there
is no guarantee that the memory really is available.  In case it
turns out that the system is out of memory, one or more processes
will be killed by the OOM killer.

A:
We don't know how long that text will be

Sure we do, we always set a maximum limit. Because all user input needs to be sanitised anyway - so we always require a maximum limit on every single user input. If you don't do this, it likely means that your program is broken since it's vulnerable to buffer overruns.
Typically you'll read each line of user input into a local array allocated on the stack. Then you can check if it is valid (are strings null terminated etc) before allocating dynamic memory and then copy it over there.
By checking the return value of malloc etc you'll see if there was enough memory left or not.

A: I made a test on linux with 8GB RAM. The overcommit has three main modes 0, 1 and 2 which are default, unlimited, and never:
Default:
$ echo 0 > /proc/sys/vm/overcommit_memory
$ ./a.out
After loop: Cannot allocate memory
size 17179869184
size 400000000
log2(size)34.000000

This means 8.5 GB were successfuly allocated, just about the amount of physical RAM. I tried to tweak it, but without changing swap, which is only 4 GB.
Unlimited:
$ echo 1 > /proc/sys/vm/overcommit_memory
$ ./a.out
After loop: Cannot allocate memory
size 140737488355328
size 800000000000
log2(size)47.000000

48 bits is virtual address size. 140 TB. Physical is only 39 bits (500 GB).
No overcommmit:
$ echo 2 > /proc/sys/vm/overcommit_memory
$ ./a.out
After loop: Cannot allocate memory
size 2147483648
size 80000000
log2(size)31.000000

2 GB is just what free command declares as free. Available are 4.6 GB.

malloc() fails in the same way if the process's resources are restricted - so this ENOMEM does not really specify much. "Cannot allocate memory" (aka ENOMEM aka 12) just says "malloc failed, guess why" or rather "malloc failed, NO more MEMory for you now.".

Well here is a.out which allocates doubling sizes until error.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <math.h>

int main() {
    size_t sz = 4096;
    void *p;
    while (!errno) {
        p = malloc(sz *= 2);
        free(p);
    }
    perror("After loop");
    printf("size %ld\n", sz);
    printf("size %lx\n", sz);
    printf("log2(size)%f\n", log2((double)sz));
}

But I don't think this kind of probing is very useful/
Buffer

we have to allocate memory to store the text in a buffer

But not the whole text at once. With a real buffer (not just an allocated memory as destination) you could read portions of the input and store them away (out of memory onto disk).
Only disadvantage is: if I cannot use a partial input, then all the buffered copying and saving is wasted.
I really wonder what happens if I type and type fast for a couple of billion years -- without a newline.

We can allocate much more than we have as RAM, but we only need a fraction of that RAM: the buffer. But Lundin's answer shows it is much easier (typical) to rely on newlines and maximum length.
getline(3)
This gnu/posix function has the malloc/realloc built in. The paramters are a bit complicated, because a new pointer and size can be returned by reference. And return value of -1 can also mean ENOMEM, not end-of-file.
fgets() is the line-truncating version.
fread() is newline independant, with fixed size. (But you asked about text input - long lines or long overall text, or both?)
Good Q, good As, good comments about "live input":
getline how to limit amount of input as you can with fgets

A: There is no standard library function that tells you how much memory is available for use.
The best you can do within the bounds of the standard library is to attempt the allocation using malloc, calloc, or realloc and check the return value - it it's NULL, then the allocation operation failed.
There may be system-specific routines that can provide that information, but I don't know of any off the top of my head.


text:
Q: C - Using strings in arrays Is it possible to create an array like this:
char name[] = {"Zed", "Roc", "Blanca"};
and then be able to:
printf("%s, %s and %s are my next-door neighbors.\n", name[0], name[1], name[2]);

I've tried it, but I keep getting errors on the array, saying "error: excess elements in char array initializer" and "error: (near initialization for 'name')" when I try to make the binary (did I use that right?).
I also get "warning: format '%s' expects argument of type 'char *', but argument [2-4] has type 'int' [-Wformat]" Character strings get a %s as a format specifier, don't they?
I'm learning C for the first time. I have a background in JavaScript, so I know how to work with arrays, which is why I ask about this; what seems obvious to me doesn't seem to work. Different language, different rules, right?
I'm also using "Learn C the Hard Way" to learn. I'll laugh if this is something that will easily be explained next chapter (spoilers).

A: Try:
char* name[] = {"Zed", "Roc", "Blanca"};
Remember, a string is an array of chars, or a pointer to char, not just a char. What you had there was one array of chars, but it needs an array of strings.


text:
Q: Get Path of Uploaded File using Python Is it possible to get the full path of the file on the user's computer being uploaded to my site?
Using os.path.abspath(fileitem.filename) simply gets me the address of where my script is executing from on my shared hosting server.
FYI: fileitem = form['file']  and form = cgi.FieldStorage()

A: No, that information isn't sent by the user, so it's not available on your end

A: To complete the answer - IE <= 7 used to send full file path instead of filename only, but IE 8 changed the default setting and sends only file names for privacy reasons.
Even if client did send the full file path, many web-based solutions (e.g PHP, Django) will strip the path and leave only filename, protecting the application against path traversal attacks. Python's cgi library is not one of them though.
So - yes, you're able to get the full file path with Python cgi, but only if client sent it using IE <= 7.


text:
Q: OpenTok iOS SDK 2.18.1 screen share quality issue We are using ReplayKit to get CMSSampleBuffers and forward them to OTVideoCaptureConsumer and after resizing ReplayKit buffers into a 1280x720 or 1024x768 buffer, we get a screen share feed, but it always becomes blurry.
After making sure we controlled the FPS sent to the videoCaptureConsumer to limit the bandwidth, we are stil unable to get a good quality image received from the media router on subscribed devices.
We validated that the image sent to OpenTok OTVideoCaptureConsumer is a clear image but the resulting stream always becomes blurry very quickly on the subscriber's end
Question: Anyone has figured out a way to get a clean OTPublisher screen sharing feed using the OpenTok iOS SDK regardless of the device's screen size?
Attempts:

*

*Different way to send frames:

I tried sending images using CVPixelBuffer and OTVideoFrame. The sample suggested by OpenTok support uses both methods CVPixelBuffer for the camera images and OTVideoFrame for the black images when no frames are received from the camera. But the resulting stream becomes blurry either way

*

*Different format and sizes:

I did not find any documentation mentioning the specs of the image expected by the iOS SDK. Is there anything available somewhere to help us understand what are the supported image format, data size limitation and supported resolutions?
I tried sending the ReplayKit buffer as is to the videoCaptureConsumer from our app and on e.g.: a 9.7 Pro iPad the native screen resolution is 1920x1440, which seems accepted by the iOS SDK (returns success), but does only render a black screen on the subscriber end.
I just don't have any other idea

*

*Retransmitting the last frame when ReplayKit stops sending frames:

I saw this behaviour in the Twilio ReplayKit sample, but should we resend the last frame when ReplayKit does not send any frame? I did not seen any doc if it's ok or if the media router will behave properly if we do so
PS: Some references I found in case it might help someone else
All I've seen in the OpenTok's support suggested sample are:

*

*the supported presets for the iOS AVCaptureSession which are then forwarded to the OTVideoCapturer (Custom-Video-Driver/Lets-Build-OTPublisher/Single-Cam-Capturer/TBExampleVideoCapture.m#L255)

*the hardcoded size for the black frames (Custom-Video-Driver/Lets-Build-OTPublisher/Single-Cam-Capturer/TBExampleVideoCapture.m#L552)

*the non processed CMSampleBuffer forwarded directly to the videoCaptureConsumer (Custom-Video-Driver/Lets-Build-OTPublisher/Single-Cam-Capturer/TBExampleVideoCapture.m#L711)
From OpenTok's doc and forum posts:

*

*OTVideoCaptureConsumer doc

*The OTPublisherKit doc mentions that the FPS should 5 FPS or lower and the code itself

*related question

*and the JS doc regarding the maximum resolutions which seem to be set on the publisher for screen share
I also found some other posts that helped understand what might be the problem:

*

*sadly not a nice one... who mentioned that images needed to be "multiple of 16"

*another sample that seem to have treated that case too and limits the output to 1280

A: I ended up using the OTVideoFrame to send the image and implementing a resend last frame logic using a DispatchWorkItem
    // We just received a frame, cancel any retransmit
    self.resetRetransmitTimer()

    let resized = cgImage
    self.checkPixelBufferSize(forImage: resized)
    let ref = self.fillPixelBuffer(withCGImage: resized)
    CVPixelBufferLockBaseAddress(ref, CVPixelBufferLockFlags.readOnly)

    self.videoFrame?.format?.pixelFormat = .ARGB
    self.videoFrame?.timestamp = timestamp
    self.videoFrame?.format?.estimatedCaptureDelay = 10
    self.videoFrame?.format?.estimatedFramesPerSecond = self.config.desiredFrameRate
    self.videoFrame?.orientation = .up

    self.videoFrame?.clearPlanes()
    self.videoFrame?.planes?.addPointer(CVPixelBufferGetBaseAddress(ref))

    self.videoCaptureConsumer?.consumeFrame(self.videoFrame!)

    self.lastReplayKitImage = cgImage
    self.lastReplayKitImageTimeStamp = timestamp

    CVPixelBufferUnlockBaseAddress(ref, CVPixelBufferLockFlags.readOnly)

    self.scheduleRetransmitTimer()


text:
Q: Overdriven/distorted sounds with Pulseaudio I'm experiencing some odd problems in some applications that use pulseaudio, in particular VLC Media Player and Skype.
The sounds reproduced by these two application sound overdriven, distorted, as if the audio is being processed by a guitar effect.
What is very odd is that the sounds being played by the two applications affect sounds played at the same time as well.
If, for instance, I'm watching a youtube video while i'm logged in skype, and one of my contacts logs in, the sound of the video gets distorted too.
It was easy to fix the problem on VLC, just by setting ALSA as the device, although this leaves some clicks in the audio, each two or three seconds.
I know somebody will suggest to simply deactivate every sound notification in Skype, but I'd rather solve this problem once and for all, before experiencing it while using another application.


text:
Q: Jsreport: launch chromium in dockerfile I'm trying to run a dockerfile which should serve my chrome-pdf generated by jsreport 2.2.0. This is the dockerfile:
FROM node:carbon
ADD . /usr/src/js-report-home
WORKDIR /usr/src/js-report-home

RUN apt-get update && apt-get install -yq libgconf-2-4

RUN apt-get update && apt-get install -y wget --no-install-recommends \
&& wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
&& sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \
&& apt-get update \
&& apt-get install -y google-chrome-unstable fonts-ipafont-gothic fonts-wqy-zenhei fonts-thai-tlwg fonts-kacst ttf-freefont \
  --no-install-recommends \
&& rm -rf /var/lib/apt/lists/* \
&& apt-get purge --auto-remove -y curl \
&& rm -rf /src/*.deb

ADD https://github.com/Yelp/dumb-init/releases/download/v1.2.0/dumb-init_1.2.0_amd64 /usr/local/bin/dumb-init
RUN chmod +x /usr/local/bin/dumb-init

ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD true

RUN npm i puppeteer

EXPOSE 5488
RUN npm install
CMD [ "npm", "start" ]

now running jsreport i get following error:
Error: Chromium revision is not downloaded. Run "npm install" or "yarn install"
at Launcher.launch (/usr/src/js-report-home/node_modules/puppeteer/lib/Launcher.js:115:15)
at <anonymous>

The error tells me to run npm install, which I do on the second last line of the dockerfile. Also I checked for chromium and it is actually installed under: puppeteer > .local-chromium > win64-579032 > chrome-win32
Any help?
EDIT: I also added an extension to my jsreport config.json, so it starts chromium without a sandbox.
{
  "shortid": "BkvRaEZLQ",
  "name": "1_Factsheet Light",
  "recipe": "chrome-pdf",
  "engine": "handlebars",
  "chrome": {
    "printBackground": true
  },
  "modificationDate": {
    "$$date": 1542121945921
  },
  "_id": "eSKSxylsIUdoPT6Z",
  "$entitySet": "templates",
  "htmlToXlsx": {
    "htmlEngine": "chrome"
  },
  "phantom": {
    "waitForJS": true,
    "fitToPage": false
  },
  "data": {
    "shortid": "rkuN61P67"
  },
  "extensions": {
   "chrome-pdf": {
    "launchOptions": {
      "args": ["--no-sandbox"]
    }
   }
  }
}

A: You need to configure jsreport/puppeteer to use the binary you explicitly downloaded using apt-get install -y google-chrome-unstable. This is done through
ENV chrome:launchOptions:executablePath google-chrome-unstable

I recommend to take a look on the official jsreport images. You would find it there.
https://hub.docker.com/r/jsreport/jsreport/
The dockerfiles can be found in the jsreport repository


text:
Q: How to tell Paris/ORM which table to use for the Model? I've just added some Joins to my application which uses Idiorm/Paris, I'm finding that when I search via Model::factory() the object returned is getting the ID from the joined object, not the 'parent' object.
How can I tell Paris which table alias should form the model?
I'm doing this in a search context, so I don't think that I can use has_many() but I'd be happy to be wrong!
Sample code:
// Find a booking with a join
$query = Model::factory('Booking');
$query->where('booking.id', '2282');
$query->join(
    'customer',
    array('booking.id', '=', 'customer.booking_id'),
    'customer'
);
$bookingWithJoin = $query->find_one();

// Find the same booking, without a join
$query = Model::factory('Booking');
$query->where('id', '2282');
$bookingWithoutJoin = $query->find_one();

// The booking with a join gets the ID of the customer it's joined with
echo $bookingWithJoin->id .' != '. $bookingWithoutJoin->id;

A: I discovered the answer was $query->select('booking.*');
Does the equivelant of
SELECT booking.* FROM bookings JOIN customer on booking.customer_id = customer.id
So the returned results won't have customer.* fields included.


text:
Q: Cannot read property 'navigation' of undefined even it's working I have this login screen, it's working but it show this warning and I'm worried about it. When I click the headerRight button, I have to logout and go back to Login Screen.
I already tried everything this website has to offer
This is my class
class AuthLoadingScreen extends Component{
    constructor(props){
        super();
        this._loadData();
    }

    _loadData = async() => {
        const isLoggedIn = await AsyncStorage.getItem('access_token');
        console.log(isLoggedIn);
        this.props.navigation.navigate(isLoggedIn == null? 'Login' : 'Home');
    }

    _removeToken = async(navigation) => {
        console.log('test');
        await AsyncStorage.clear();
        navigation.navigate('Login');
    }

    render(){
        return(
            <View><ActivityIndicator/></View>
        );
    }
}

And this is where I'm calling _removeToken function
const StackNavigator = createStackNavigator({
    AuthLoading: AuthLoadingScreen,
    Login: {
        screen: Login,
    },
    Register: {
        screen: Register,
    },
    Home: {
        screen: TabNavigator,
        navigationOptions: ({navigation}) => ({
            title: 'Insta Clone',
            headerLeft: null,
            headerTitleStyle: {
                textAlign:"center",
                flex:1
            },
            headerRight: (
                <Button
                    icon={
                        <Icon
                        name='sign-out'
                        type='octicon'
                        color='black'
                        />
                    }
                    onPress={() => (new AuthLoadingScreen)._removeToken(navigation)} // <--- HERE
                    buttonStyle={ {backgroundColor: 'transparent'} }
                />
            ),
            headerLeft: (
                <Button
                    icon={
                        <Icon
                        name='info'
                        type='octicon'
                        color='black'
                        />
                    }
                    onPress={() => alert("Created by Matheus Melo")}
                    buttonStyle={ {backgroundColor: 'transparent'} }
                />
            ),
        })
    },
});

A: You can directly navigate to Login, no need to use AuthLoadingScreen reference, here's how the updated code should look like:
const removeToken = async(navigation) => {
        console.log('test');
        await AsyncStorage.clear();
        navigation.navigate('Login');
    }
const StackNavigator = createStackNavigator({
    AuthLoading: AuthLoadingScreen,
    Login: {
        screen: Login,
    },
    Register: {
        screen: Register,
    },
    Home: {
        screen: TabNavigator,
        navigationOptions: ({navigation}) => ({
            title: 'Insta Clone',
            headerLeft: null,
            headerTitleStyle: {
                textAlign:"center",
                flex:1
            },
            headerRight: (
                <Button
                    icon={
                        <Icon
                        name='sign-out'
                        type='octicon'
                        color='black'
                        />
                    }
                    onPress={() => removeToken(navigation)}
                    buttonStyle={ {backgroundColor: 'transparent'} }
                />
            ),
            headerLeft: (
                <Button
                    icon={
                        <Icon
                        name='info'
                        type='octicon'
                        color='black'
                        />
                    }
                    onPress={() => alert("Created by Matheus Melo")}
                    buttonStyle={ {backgroundColor: 'transparent'} }
                />
            ),
        })
    },
});


text:
Q: bash - surround all array elements or arguments with quotes I want to write a function in bash that forwards arguments to cp command.
For example:
for the input
<function> "path/with whitespace/file1" "path/with whitespace/file2" "target path"

I want it to actually do:
cp "path/with whitespace/file1" "path/with whitespace/file2" "target path"

But instead, right now I'm achieving:
cp path/with whitespace/file1 path/with whitespace/file2 target path

The method I tried to use is to store all the arguments in an array, and then just run the cp command together with the array.
Like this:
function func {
    argumentsArray=( "$@" )
    cp ${argumentsArray[@]}
}

unfortunately, It doesn't transfer the quotes like I already mentioned, and therefore the copy fails.

A: Just like $@, you need to quote the array expansion.
func () {
    argumentsArray=( "$@" )
    cp "${argumentsArray[@]}"
}

However, the array serves no purpose here; you can use $@ directly:
func () {
    cp "$@"
}


text:
Q: custom page under single post type name not working post type page: https://prnt.sc/HMNzcsQuqqIC
single-post type :image link: https://prnt.sc/I3COwDGVwO6O
I created a custom post type page {post type name= services} and a single post page {single-services}. all are working but the title problem I am facing here. When I post on the custom post page is that working. On the other side when I click the post link on the title. that is a show similar to all posts. But I want when I click a post link only to show this post. Please help

              <?php
              $customservice = new WP_Query(array(
                'post_type' => 'services',
                'posts_per_page' => -1,
                'order' => 'ASC'
                ));
                while ( $customservice->have_posts() ) : $customservice->the_post();?>
                <?php the_post_thumbnail(); ?>

                    <a href="<?php the_permalink(); ?>">
<?php the_title();?>

                    <?php the_content(); ?>

               <?php endwhile;?>

enter code here


text:
Q: Deshabilitar un checkbox de la misma fila Tengo realizado una tabla que contiene dos columnas de checkbox que representan una condición: SI y NO.

Cada checkbox es un objeto que va formando un array según lo que se vaya seleccionando. La propiedad "Condición" del objeto en un inicio es null pero lo edito según el checkbox que escoga. Lo que deseo hacer es deshabilitar el primer checkbox o el segundo, según lo que seleccione, para evitar que se pueda seleccionar dos condiciones en una misma fila. Pensé en recorrer la columna pasando también el index mediante el evento change pero no comprendo como podría hacerlo.
El HTML que tengo:
<form [formGroup]="demoFormGroup" (ngSubmit)="submit()" style="margin-top:50px; margin-bottom:30px">

                SI
                NO

                {{x.Descripcion}}

                    <mat-checkbox class="example-margin" (change)="onChange1($event,i)" [value]="x"
                        [disabled]="selected">
                    </mat-checkbox>

                    <mat-checkbox class="example-margin" (change)="onChange2($event,i)" [value]="x"
                        [disabled]="selected">
                    </mat-checkbox>

<button>Submit</button>
</form>

{{ demoFormGroup.value | json }}

Y el .TS
import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray, FormBuilder } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  demoFormGroup: FormGroup;
  data: any;
  selected: false;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.demoFormGroup = this.fb.group({
      info: this.fb.array([])
    });

    setTimeout(res => {
      this.data = [
        {
          Id: 4,
          Descripcion: 'Opcion 1',
          Condicion: null
        },
        {
          Id: 6,
          Descripcion: 'Opción 2',
          Condicion: null
        },
        {
          Id: 10,
          Descripcion: 'Opción 3',
          Condicion: null
        }
      ];
    });
  }
  onChange1(event, i) {
    const x = (<FormArray>this.demoFormGroup.get('info')) as FormArray;
    event.source.value.Condicion = 1;
    this.onEventChecked(event, x);
  }
  onChange2(event) {
    const y = (<FormArray>this.demoFormGroup.get('info')) as FormArray;
    event.source.value.Condicion = 2;
    this.onEventChecked(event, y);
  }
  onEventChecked(event, ctrl) {
    if (event.checked) {
      ctrl.push(new FormControl(event.source.value));
    } else {
      const i = ctrl.controls.findIndex(
        (x: any) => x.value === event.source.value
      );
      ctrl.removeAt(i);
    }
  }
  submit() {
    console.log(this.demoFormGroup.value);
  }
}

La demo la subí a stackblitz DEMO

A: Solo se necesita una función onChange(), como parámetro recibe el objeto actual en la iteración y un valor booleano indicando si se activará o se desactivará.
Adicional a eso el estado checked del checkbox dependerá de lo siguiente:
[checked]="x.Condicion" si Condicion es verdadero entonces el checkbox se marca.
[checked]="x.Condicion != null && !x.Condicion" Si Condicion  no es null y tiene un valor false entonces el checkbox no se marca.
Si Condicion está con su valor inicial null ambos checkbox estarán desmarcados.

    <mat-checkbox class="example-margin" (change)="onChange(x,true)" [checked]="x.Condicion" [disabled]="selected">
    </mat-checkbox>

    <mat-checkbox class="example-margin" (change)="onChange(x,false)" [checked]="x.Condicion != null && !x.Condicion"
        [disabled]="selected">
    </mat-checkbox>

La función onChange() queda así:
onChange(option : any, enabled : boolean) {
    option.Condicion = enabled
  }

Solo asigna el valor recibido a la propiedad Condicion.
Demo


text:
Q: Is there a way to not have Lion not launch apps from previous startup?
Possible Duplicate:
Reopen windows when logging back in - NOT
How can I keep restore for apps in Lion without having session restore when I log in?

I've heard conflicting info on this - seems like a good place for an option on startup. Any ideas? I just want a clean slate and find it annoying.

A: You can change this in System Preferences > General. Look for the "Restore windows when quitting and re-opening apps" check box and uncheck it.


text:
Q: Cannot see getElementById function in node properties (Web Inspector Safari) As the title says I can't see this function. I'm afraid that there is more function that I can't see. Any of you guys has the same? Maybe I should use other browser for better DOM Inspector.

A: Because if you look at the title of what is open in the right column on your image, it will say Element. And getElementById belongs to Document interface, and not to Element. All DOM interfaces are here.


text:
Q: ConstraintValidatorContext stores previous nodes when it shouldn't I have this class
@HasNose
@HasMouth
public class Person {

    String fieldA;
    String fieldB;
    // getters and setters

}

Now the custom annotations validator look something like this
// validator of @HasNose
@Override
public boolean isValid(Object object,
                        ConstraintValidatorContext context) {

    // some tests that determine there is an error
    context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("Some message")
            .addNode("fieldA")
            .addConstraintViolation();

}

and
// validator of @HasMouth
@Override
public boolean isValid(Object object,
                        ConstraintValidatorContext context) {

    // some tests that determine there is an error
    context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("Some message")
            .addNode("fieldB")
            .addConstraintViolation();

}

Running this produces the exception:
java.lang.IllegalStateException: JSR-303 validated property 'fieldA.fieldB' does not have a corresponding accessor for Spring data binding - check your DataBinder's configuration (bean property versus direct field access)
at org.springframework.validation.beanvalidation.SpringValidatorAdapter.processConstraintViolations(SpringValidatorAdapter.java:148)
at org.springframework.validation.beanvalidation.SpringValidatorAdapter.validate(SpringValidatorAdapter.java:101)
at org.springframework.validation.DataBinder.validate(DataBinder.java:722)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.validateIfApplicable(ModelAttributeMethodProcessor.java:154)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:107)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:74)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:155)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:117)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:680)

For some reason "ConstraintValidatorContext" is concatenating both fields. Debugging shows that the attribute "propertyPath" comes already filled out with "fieldA".
I thought it should be at the root level per constraint validator doesn't it?

A: I found the solution for my own problem, I was using hibernate-validator-4.2.0.BETA2. Switching to hibernate-validator-4.2.0.FINAL solved the issue.
Lesson to learn: keep your libs updated...


text:
Q: How to attach file using actionFunction Could you help me please? I want to implement attaching files to Cases in SalesForce.
There is recomanded way which using apex:inputFile element, but I can't use it, because on page I have to use more rerendering scopes.
So I decided to implement it via standard html input and action function with parameters (where content of file is passed in parameter to apex class).
Visualforce:
<apex:form id="techForm" enctype="multipart/form-data">
<apex:actionFunction name="fillAttachment" action="{!formController.FillAttachment}" reRender="attachmentsBlock">
<apex:param assignTo="{!formController.handleFileContent}" name="handleFileContent" value="" />
</apex:actionFunction>
<script type="text/javascript">
function check_extension(filename) {
var files = document.getElementById('attachment').files;
var file = files[0];
fillAttachment(file);
}
</script>
<input type="file" accept=".gif, .jpg, .jpeg, .tif, .tiff, .png, .pdf" onChange="check_extension(this.value)" class="hidden" value="" filename="attachment" id="attachment" />
</form>

Apex Class:
public class ContactUsController {
    public  List<Attachment> attachments { get; set; }
    public String handleFileContent { get; set; }
public void FillAttachment() {
if(this.handleFileContent != null && this.handleFileContent.length() > 0) {
Attachment toAttach = new Attachment(body = Blob.valueOf(this.handleFileContent));
this.attachments.add(toAttach);
}
}
}

The problem of this approach is that in this way, i got "Regex too complicated" error.
S

*

*o, I tried to check heap size
(http://blog.jeffdouglas.com/2010/08/16/managing-the-heap-in-salesforce-com/),but it is no problem.

*I also tryied to use Transcient method, but it  does not work

*Finnaly I tried to use future method, but it is static, so it is not
possible for me to use it.
I suggest that problem is that I exceed limit of view stat
Can you help me?
To Sum Up. Is there any way, how to send file from visualforce page using javascript and actionfunction to apex class? I can not use apex:imputFile because I have to use more rerender scopes on that page. I hope that there will be some workaround.
(I thinking about iframe page using apex:imputFile embedded to my page which handle uploading attachments and then via timpestamp-identifiers map it to relevant Case. But I think that it is "weird" way to upload files.)
Thank you for your answer.
Martin


text:
Q: Access to fields in IF sentence in DAX in Power BI Desktop When I use SUM for example the intellisense of the editor shows me the columns of my table but when I use IF or Switch I'm not shown any column.
In this example of If (https://powerbi.microsoft.com/es-es/documentation/powerbi-desktop-tutorial-create-calculated-columns/) the column between [] works fine but when I put my column between [] I have error
error if

Any idea please?
Regards

A: I can see you are creating a measure while in the tutorial they are creating a calculated column. Measures and Calculated columns behave different, while creating a calculated column the expression you are using takes the context of each row so you can reference any column directly by [Column].
However measures evaluate in different context so they need an aggregation function to determine the value of your columns.
EXAMPLE: Calculated Column.
Is Red Calculated Column = IF([Color]="Red","Yes","No")

EXAMPLE: Measures.
Is Red Measure = IF(FIRSTNONBLANK([Color],0)="Red","Yes","No")

Note I used FIRSTNONBLANK aggregation function to access the [Color] column from a measure.
The above expression could not work for you depending on your measure, I only posted it for example purposes.

A: I found the answer
TotalHoras = SUMX(Horas;if(Horas[Tipo]="M";Horas[Duration]/60;Horas[Duration]))

Like @alejandrozuleta says Measures need an aggregation function to works


text:
Q: Соединить строки ListBox в одну Подскажите, пожалуйста, как можно объединить все строки ListBox в одну?
Делаю вот так, но кажется что-то неверно:
 begin
  i := 1;
  while i < ListBox1.Count do
    s := ListBox1.Items[i] + '+' + ListBox1.Items[i + 1];
  Inc(i);
  Edit4.Text := s;
end;

A: Можно использовать стандартные методы свойства TListBox.Items класса TStrings
ListBox1.Items.Delimiter := '+';
Edit4.Text := ListBox1.Items.DelimitedText;

A: Обычно, склеивается вот так:
uses StrUtils;

...

s := '';
for I := 0 to ListBox1.Count - 1 do
  s := s + IfThen(s <> '', '+') + ListBox1.Items[I];

Edit4.Text := s;


text:
Q: Store a user input string of integers into an integer array mips assembly just like the title states, I am trying to write a program in MIPS assembly that will take a string input by a user of 4 integers between 0-9 separated by spaces and store each of those numbers as an integer into an array. Here's what I have so far:

.data
input1: asciiz "Input Row 1: "
row1: .asciiz "Row 1: "
array: .space 16
list: .space 8
.text
la $s0, array              #load address of array to s0
li $s1, 0                  #index of array
li $v0, 4                  #call for print string
la $a0, input1             #load string to be printed
syscall
li $v0, 8                  #call for user input
la $a0, list               #address of where the input will be stored
li $a1, 8                  #space allowed for input
syscall
loop:
la $t0, list               #load address of the string
add $t2, $zero, $zero      #index of the string
load:
sll $t3, $t2, 1            #multiply string index by 2 to skip spaces
sll $t4, $s1, 2            #multiply index of array by 4 for size of word
addu $t0, $t0, $t3         #position string
addu $s0, $s0, $t4         #position array
lbu $t1, 0($t0)            #load byte of the string to t1
addiu $t1, $t1, -48        #convert char to integer
sb $t1, 0($s0)             #store byte into the array
addi $t2, $t2, 1           #increment index of string by 1
addi $s1, $s1, 1           #increment index of array by 1
blt $t2, 4, load           #if the index of the string is less than 4, load the next character
li $v0, 11                 #printing first input as integers from here
addi $a0, $zero, 0xA       #new line ascii character
syscall
li $v0, 4                  #call for print string
la $a0, row1               #load string to be printed
syscall
li $v0, 1                  #print integer call
lb $a0, -24($s0)           #load first number input
syscall
li $a0, 32
li $v0, 11                 # syscall number for printing character
syscall
li $v0, 1
lb $a0, -20($s0)           #load second number input
syscall
li $a0, 32
li $v0, 11                 # syscall number for printing character
syscall
li $v0, 1
lb $a0, -16($s0)           #load third number input
syscall
li $a0, 32
li $v0, 11                 # syscall number for printing character
syscall
li $v0, 1
lb $a0, -12($s0)           # load fourth number input
syscall
exit:
li $v0, 10
syscall

The two problems I am having are that I expected the offset of the array to be at -12 (4 words x 4 bytes - 4 for 0 start point), but it starts at -24, and for the 3rd input, no matter what it is, the int 0 gets stored. I am running this program in MARS 4.5. Sample output below:
Input Row 1: 1 2 3 4
Row 1: 1 2 0 4
-- program is finished running --

Eventually I am going to have the user input 4 strings to create a 4x4 matrix and store all of those strings in the same array.

A: Jester pointed out to me in the comments what I was doing incorrectly. Instead of incrementing the array address by 4 every time, I was adding 4 more than the last increment. So I was adding 0 the first time, then 4, then 8 to that, putting me at 12, and then 12 more, which is why I ended up at an offset of 24 instead of the expected 12. I moved the declaration of la $s0, array and la $t0, list into the loop, so that it continues to set it back to the base address.
The new loop looks like the following:
loop:
add $t2, $zero, $zero     #index of the string
load:
la $s0, array              #load address of array to s0
la $t0, list               #load adress of the string
sll $t3, $t2, 1            #multiply string index by 2 to skip spaces
sll $t4, $s1, 2            #multiply index of array by 4 for size of word
addu $t0, $t0, $t3         #position string
addu $s0, $s0, $t4         #position array
lbu $t1, 0($t0)            #load byte of the string to t1
addiu $t1, $t1, -48        #convert char to integer
sb $t1, 0($s0)             #store byte into the array
addi $t2, $t2, 1           #increment index of string by 1
addi $s1, $s1, 1           #increment index of array by 1
blt $t2, 4, load           #if the index of the string is less than 4, load the next character
li $v0, 11                 #printing first input as integers from here
addi $a0, $zero, 0xA
syscall
li $v0, 4                  #call for print string
la $a0, row1               #load string to be printed
syscall
li $v0, 1
lb $a0, -12($s0)
syscall
li $a0, 32
li $v0, 11                 # syscall number for printing character
syscall
li $v0, 1
lb $a0, -8($s0)
syscall
li $a0, 32
li $v0, 11                 # syscall number for printing character
syscall
li $v0, 1
li $a0, 32
li $v0, 11                 # syscall number for printing character
syscall
li $v0, 1
lb $a0, 0($s0)
syscall
exit:
li $v0, 10
syscall

Credit to Jester for steering me in the right direction.


text:
Q: Static methods vs non static methods in .Net I'm workin with an API in .Net Core and recently I had a situation where the business layer was with all static methods. What kinds of problems can this cause?

*

*When the API has a request, it's instantiates a new thread, correct? And the static methods will then occupy double the memory?

*Can there be performance loss? Because there will be more concurrency between threads and, depending on the processor of the machine, this will be critical.

*The memory will be released when the application dies. That is, ever will occupy an extra part of memory, while the application is running.

A: For rendering services via an API, you can't declare your methods (actions to be specific) statically; because, the API context or better said the controller has to be initialized (per request) in order to render the service (get the incoming request and write the response back to the http context).
But if an API is not the case, static method declaration would in fact help you with performance, as it can be called statically and without the need to instantiate an object. However, it is not a good design (neither is it actually bad). What matters is that, you have to analyze the scenario well to determine if you can really take advantage of modularity earned by functional programing rather than an object oriented approach.
To break it down more technically for you, there is a design pattern commonly known as the Singleton pattern in which an object is created only once during the life cycle of a program, and a single instance is shared with all entities trying to access the type. That said; it is not bad at all, but once again, you have to well analyze the scenario.
For example: a singleton entity framework context is a bad idea, because the context may get disposed and you would lose all the changes, tracking data, etc.   On the other hand, a singleton ADO.Net context is a good idea if you follow the concept of single responsibility for each of your static methods.


text:
Q: QCompleter and QListWidget as custom popup issue I have a QCompleter using a QStringListModel for my QPlainTextEdit (check this example):
  QStringListModel* model = new QStringListModel(names);
  QCompleter* completer = new QCompleter(model);
  completer->setCompletionMode(QCompleter::PopupCompletion);
  completer->setModelSorting(QCompleter::UnsortedModel);

It works fine. Now I need some Icon, Tooltips for each suggestion I'm trying to use a QListWidget as custom popup:
  QListWidget* w = new QListWidget();
  foreach(name, names) {
    QListWidgetItem* i = new QListWidgetItem(name);
    i->setIcon(/*my Icon*/);
    i->setToolTip("");
    w->addItem(i);
  }
  completer->setPopup(w);

The popup ok, just like I need, but the completion no more work. I cannot type the text to make it filter the suggestion, just Up/Down key.
I have try:
  completer->setModel(w->model());

but no help!
What is my misstake or just QStringListModel give me the ability to filter the suggestions? What do you suggest?
Thanks you!

A: I mostly deal with PyQt, but same deal.  My syntax may be off, but you should use a QStandardItemModel vs. a QStringListModel.  From there, you can leave it as the standard popup (QListView)
Something like:
QStandardItemModel* model = new QStandardItemModel();

// initialize the model
int rows = names.count();  // assuming this is a QStringList
model->setRowCount(rows);
model->setColumnCount(1);

// load the items
int row = 0;
foreach(name, names) {
    QStandardItem* item = new QStandardItem(name);
    item->setIcon(QIcon(":some/icon.png");
    item->setToolTip("some tool tip");
    model->setItem(row, 0, item);
    row++;
}

completer->setModel(model);
completer->popup()->setModel(model); // may or may not be needed


text:
Q: php include wont show my content in the php file So, i have this form in a php file and i want it to show in this sliding div but it doesn't show any of the php file with my include file.  ANy suggestions?
I think im trying to inlcude the php file incorrectly
Here is the doc:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <title></title>

                Expanding/Collapse

                Google

                <?php include("test.php"); ?>

And here is the php file
<?php
if ($_POST["email"]<>'') {
    $ToEmail = 'email@email.site';
    $EmailSubject = 'Portfolio Contact .com';
    $mailheader = "From: ".$_POST["email"]."\r\n";
    $mailheader .= "Reply-To: ".$_POST["email"]."\r\n";
    $mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";
    $MESSAGE_BODY = "Name: ".$_POST["name"]."";
    $MESSAGE_BODY .= "Email: ".$_POST["email"]."";
    $MESSAGE_BODY .= "Comment: ".nl2br($_POST["comment"])."";
    mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
?>
Your message was sent
<?php
} else {
?>
<form action="test.php" method="post">

Your name:
<input name="name" type="text" id="name" size="32">

Email address:
<input name="email" type="text" id="email" size="32">

Comment:
<textarea name="comment" cols="45" rows="6" id="comment" class="bodytext"></textarea>

<input type="submit" name="Submit" value="Send">

</form>
<?php
};
?>

A: To easily eliminate the possibility that it cannot find the files test.php, replace your include() for require(). It does exactly the same, with the slight difference that not finding the file causes PHP to throw a fatal E_COMPILE error, thus making it blaringly obvious that something went wrong.
To aid your bug fixing, add the following two line to the very top of your PHP script (the main file):
ini_set('display_errors', 1);
error_reporting(E_ALL);

This will cause it to display all errors and notices right on the page, instantly showing you what went wrong in which file, on which line. Make sure you only use this in development though, you don't want your users to see detailed error messages about your back-end code.

A: remove include file and use this jQuery Load, so your form will be load within div id box2

and change this if to @$_POST["email"]<>'' with at sign and your error will be hide

A: Try viewing the page source and see if it is being included there. Your php file is included inside #box2, which has display set to none in the css, so it won't render even if it is being included.


text:
Q: How to get all the local "peaks" from a picture? I would like to get all the small peaks from the picture below. I would also like to avoid getting the big peak (on the right), but I can exclude that based on the area. The image is a result of Sobel operator but this is not important. It will be used as markers for watershed algorithm. This is not the only picture I have to process and I can't relay on the values of the peaks only on the fact that they are "local maximums". Notice that contour detection won't work as some small bumps are connected. The picture:

A: You may find Chapter 4 "Peaks and Ridges" of my thesis 1999 useful. It uses the concept of the watershed algorithm, implemented using Vincent's ordered pixel implementation. Algorithm details are in the thesis. I have not been working in the area for many years so have not done an opencv implementation.
@Alessandro Jacopson provides the following link in another SO watershed question :
VINCENT, Luc; SOILLE, Pierre. Watersheds in digital spaces: an efficient algorithm based on immersion simulations. IEEE transactions on pattern analysis and machine intelligence, 1991, 13.6: 583-598.


text:
Q: Delete a directory only if it exists using a shell script I have a shell (ksh) script. I want to determine whether a certain directory is present in /tmp, and if it is present then I have to delete it. My script is:
test
#!/usr/bin/ksh
# what should I write here?
if [[ -f /tmp/dir.lock ]]; then
    echo "Removing Lock"
    rm -rf /tmp/dir.lock
fi

How can I proceed? I'm not getting the wanted result: the directory is not removed when I execute the script and I'm not getting Removing Lock output on my screen.
I checked manually and the lock file is present in the location.
The lock file is created with set MUTEX_LOCK "/tmp/dir.lock" by a TCL program.

A: For directory check, you should use -d:
if [[ -d /tmp/dir.lock ]]; then
    echo "Removing Lock"
    rm -rf /tmp/dir.lock
fi

A: In addition to -f versus -d note that [[ ]] is not POSIX, while [ ] is. Any string or path you use more than once should be in a variable to avoid typing errors, especially when you use rm -rf which deletes with extreme prejudice. The most portable solution would be
DIR=/tmp/dir.lock
if [ -d "$DIR" ]; then
    printf '%s\n' "Removing Lock ($DIR)"
    rm -rf "$DIR"
fi


text:
Q: Unity 5.2 UNet: Release a GameObject from it's owner I am testing UNET (Unity 5.2) but is running into problem with things that probably should be very simple.
I have an Orange fruit (GameObject) that i can drag and have attached the network transform in code. When releasing the mouse (Mouse Up) I want to release the ownership of the Orange so none owns it, want later to attach to another player. I have tested with ReplacePlayerForConnection and a few other things but totally screwed up the code.
I have now reset everything and must ask for some help how to do this.
The scripts i have, attached to the Orange GameObject, is:
1
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;

public class orange : NetworkBehaviour {

float distance = 10;

void Start() {

    if (isLocalPlayer) {

        //GameObject.Find("Main Camera").SetActive(false);

    }

}

void OnMouseDrag() {

    Vector3 mousePosition = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, distance);
    Vector3 objPosition = Camera.main.ScreenToWorldPoint (mousePosition);

    transform.position = objPosition;

}

void OnMouseUp() {
    print (">>> MOUSE UP <<<");

    if (isLocalPlayer) {
        GetComponent<NetworkIdentity> ().localPlayerAuthority = false;
        GetComponent<NetworkIdentity> ().serverOnly = false;
    }

}

Here is scrip #2 attached to the Orange GameObject:
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;

public class Orange_SyncPosition : NetworkBehaviour {

[SyncVar] // Server will automatically transmit this value to all players when it changes
private Vector3 syncPos;

[SerializeField] Transform myTransform;
[SerializeField] float lerpRate = 15;

void FixedUpdate () {
    TransmitPosition ();
    LerpPosition ();
}

void LerpPosition() {

    if (!isLocalPlayer) {
        myTransform.position = Vector3.Lerp(myTransform.position, syncPos, Time.deltaTime *lerpRate);
    }

}

[Command]
void CmdProvidePositionToServer (Vector3 pos) {
    syncPos = pos;
}

[ClientCallback]
void TransmitPosition () {

    if (isLocalPlayer) {
        CmdProvidePositionToServer (myTransform.position);
    }

}
}

A: Use NetworkServer.ReplacePlayerForConnection():
// Player is a NetworkBehaviour on the existing player object
void ReplacePlayer (Player existingPlayer) {

    var conn = existingPlayer.connectionToClient;
    var newPlayer = Instantiate<GameObject>(playerPrefab);

    Destroy(existingPlayer.gameObject);
    NetworkServer.ReplacePlayerForConnection(conn, newPlayer, 0);

}

A: Use AssignClientAuthority / RemoveClientAuthority
And never touch these parameters at runtime:
GetComponent<NetworkIdentity> ().localPlayerAuthority = false;
GetComponent<NetworkIdentity> ().serverOnly = false;


text:
Q: How to convert COM dispid to memberid in .NET? I have a "System.Collections.ArrayList" (from mscoree.dll) with CLSID {6896b49d-7afb-34dc-934e-5add38eeee39} and also I have TypeLib for it. For example, this TypeLib has co-class "IList" with function "Add" where MEMBERID is 0x60020002.
I checked with help of "GetIDsOfNames" that MEMBERID is different from DISPID for the same function "Add". DISPID is "0x60020020" (see last 2 digits).
The problem is I need to get member name having only DISPID and dispatch interface. When I use "GetNames" with DISPID I don't get anything, although in other libs everything is fine. On the other hand, if I use MEMBERID, I get the desired result "Add". I also can't parse typelib to get member names, cuz MEMBERID is not eq DISPID.
How could I convert DISPID to MEMBERID? Or might be it is possible to get member name using DISPID?
UPDATE 2022-08-16
Added example to demonstrate:

*

*I have "IDispatch" interface and make first call to "GetIDsOfNames" with parameter "Add". The result is 0x60020020.

*Then I make more calls to get class info:
IDispatch -> QueryInterface(IID_IProvideClassInfo) -> GetClassInfo(...) -> GetTypeAttr(...) -> guid

Result guid is: CLSID_System.Collections.ArrayList {6896B49D-7AFB-34DC-934E-5ADD38EEEE39}

*I'm going to open OLE/COM object viewer and see that ArrayList is a coclass with 6 interfaces, where the only IList interface has method "Add" with Id == 0x60020002 (see last 2 digits are different from the above).

I do really expect to see here 0x60020020 same as the result of call to GetIDsOfNames. But id is different.
Moreover, when I ask id of methods "Contains" and "Clear", I get 0x60020021 and 0x60020022, but not 0x60020003 and 0x60020004 from the Typelib.
Where am I wrong?
P.S. I checked both mscorlib.tlb and mscoree.tlb. All of them have same id (0x60020002) for "Add".

A: The situation you describe is absolutely forbidden.
The documentation of MEMBERID says

The MEMBERID of an IDispatch interface MUST be the same as its DISPID

If you haven't made any mistake transcribing the MEMBERID and DISPID, they must be from different types.  When viewing ArrayList through COM goggles, you'd have a coclass for ArrayList, an interface for the ArrayList class, and interfaces for each .NET interface implemented by ArrayList.  More than one of these have a method named Add.

A: I looked at the logic of the DISPID assignment function in the "mscorwks.dll" library and found that:
DISPID is not the same as MEMBERID.
DISPID Value is assigned dynamically in the function:
mscorwks.private: void __cdecl ComMTMemberInfoMap::AssignDefaultDispIds(void)

Given the listing of the function, we can find that it operates on an array of class methods and assigns a DISPID to each method in order, starting with the first one.
The first method is always constant 0x60020000:
00007FFB19A8F67F | 4C:8D69 40          | lea r13,qword ptr ds:[rcx+40]
00007FFB19A8F683 | BF 00000260         | mov edi,60020000

The value of each subsequent DISPID increases by one. The member "Add" gets the value 0x60020020. There is no connection to TypeLib member ids.
With this information, we understand that the call to "GetIDsOfNames" produces the correct result 0x60020020. Thus, we cannot guarantee that by comparing DISPID and MEMBERID from TypeLib we will get the desired method name "Add".


text:
Q: How can I use the Translator service outside of a controller in Symfony 3? I have a form type:
<?php

// src/AppBundle/Form/ProductType.php
namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class ProductType extends AbstractType
{

    private $translator;

    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', TextType::class)
            ->add('save', SubmitType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Product',
        ));
    }
}

As you see I am already attempting to set up my form type to inject the translator. In my services I have:
parameters:
#    parameter_name: value

services:
    app.form.product:
        class: AppBundle\Form\ProductType
        arguments: ["@translator"]

But am receiving the following error:

Catchable Fatal Error: Argument 1 passed to AppBundle\Form\ProductType::__construct() must implement interface

Symfony\Component\Translation\TranslatorInterface, none given, called
  in
  /path/to/symfony/bundle/vendor/symfony/symfony/src/Symfony/Component/Form/FormRegistry.php
  on line 85 and defined....

Can someone tell me what gives? I am pretty sure the service type is wrong but cant find the one I need to save my life.

A: Check in the service definition of your form that you have correctly tag the service as a form.type as described here in the doc.
In according with the news announcement, from the version 2.6 the translator component is defined as service like translator.default.
As Example, you should have something like:
services:
    app.form.product:
        class: AppBundle\Form\ProductType
        arguments: ["@translator.default"]
        tags:
            - { name: form.type }

hope this help


text:
Q: Object as Map Key in Typescript I wanted to create a Map object with an object as key and a number as value in Typescript. I defined the map object as follows:
myMap: Map<MyObj,number>;
myObj: MyObj;

and when I try to add a pair to this map object:
this.myMap[myObj]=1;

It tells me that TS2538 Type 'MyObj' cannot be used as an index type. Is this possible in Typescript?

A: You have to use the set function e.g.
this.myMap.set(myObj, 1);


text:
Q: Discretize Integral
With minor edit with respect to the comments.

Suppose I want to evaluate
\begin{align}
\int^{T}_0{e^{-t}x(t)dt}.
\end{align}
However, I can only approximate the continuous function $\mathbb{R}_+ \ni t \mapsto x(t)$ by a discrete sequence $\{x_t : t \in \{0,\Delta t, 2\Delta t, \ldots,N\}\}$ where $\Delta t := T/N$.

*

*Is the following true (given $N \to \infty$)?
\begin{align}
\int^T_0{e^{-t}x(t)dt} \approx \sum^{N}_{t=0}{e^{-t}x_t\Delta dt}
\end{align}


text:
Q: Consider the sequence $a_1 = 24^{1/3}$ $a_{n+1} = (a_n + 24)^{1/3},n ≥ 1.$ Then what is the integer part of $a_{100}$? QUESTION: Consider the sequence
$a_1 = 24^{1/3}$
$a_{n+1} = (a_n + 24)^{1/3},n ≥ 1.$
Then what is the integer part of $a_{100}$ ?
MY APPROACH: I tried this one really hard but couldn't get the trick.. I used log, but that doesn't really help and the problem becomes more and more complex, so I am avoiding a confusing solution here..
Then I tried by defining a function say $$f(x)=(x+24)^\frac{1}3$$ Therefore by computing the derivative of $f$ we find that the rate at which the function increases, decreases with increase in x. Which also is quite clear from intuition. But I could not apply the result to solve the problem.
Can we form a recursive series for it? Any help will be much appreciated. Thank you so much.

A: Hint: Prove by induction that $2 < a_n < 3$ for all $n$.

A: If $x<3$, then $f(x)<(3+24)^{1/3}=3$.
If $x\geq 0$, then $f(x)\geq(0+24)^{1/3}>2$.
So what can you say about $a_{100}=f^{100}(0)$?