text:
Q: How do I use the `nextLink` property of a result? A query result object returns with nextLink set either to a URL for the next page of results as a string or a null, depending on whether there's another page after the current one. The docs are quite clear about this, but there's nothing in them about how to take that link and make another request for the next page.
I've been digging through the source and have only found that it appears as if there really isn't any way to make use of this value as anything other than a boolean telling me that there's more. To leave such an obviously loose end, even in a beta API, just doesn't sound like Google, so I must be missing something somehow.
The way my code is set up, I can't just reuse the request data that generated the initial request. I have separate logic to make the initial request and to parse the result-set into a usable form. That, and knowing that link is exposed as if it's meant to be used hints that there's a cleaner way than to modify the initial request. Just, how do I do that?

A: I have something that seems to work. The important bit is at the bottom, where I take nextLink and use the pieces to make a fresh query. It isn't ideal, but it works better than trying to cURL things manually, as everything else online seems to suggest. Google_Service_Analytics_GaData will, of course, vary by which service is being used.
do {
    $rows = $results->getRows();

    foreach ($rows as $row) {
        $record = array();

        foreach ($row as $i => $field) {
            $name = $headers[$i]->name;

            switch($headers[$i]->dataType) {
                case 'FLOAT':
                    $record[$name] = (float) $field;
                    break;
                case 'INTEGER':
                    $record[$name] = (int) $field;
                    break;
                default:
                    $record[$name] = (string) $field;
            }
        }

        $records[] = $record;
    };

    $nextLink = $results->getNextLink();

    if ($nextLink) {
        /* The GA API doesn't have anything to actually USE The link
         * they so helpfully supply, so we have to disassemble it and
         * make a new query off of it. Internally,
         * $this->gaService->data_ga calls $this->gaService->call.
         * These are on `Google_Service_Analytics_DataGa_Resource` and
         * `Google_Service_Resource`, respectively.
         */
        $options = [];
        parse_str(substr($nextLink, strpos($nextLink, '?') + 1), $options);

        $results = $this->gaService->data_ga->call('get', [$options], "Google_Service_Analytics_GaData");
    }
} while ($nextLink);


text:
Q: Making automated 2D machine movement with C I have this little project, that is a machine which movement in 2 Dimensions, "walking" 1 block at time. So I´m starting with programming and I would like to print the numbers in order, like the machine is in movement.
Like this:
X O O O O
O O O O O
O O O O O
O O O O O
then the next move would be
O O O O O
X O O O O
O O O O O
O O O O O
then go until the end of column, so it moves to another column and make the movement backyards,(or it could go for the first dot of the new column and repeat the movement )
What I´m doing is one matrix and trying to make a for loop with restrictions but it isn't working.. I'm new to C language as well.
Remember that for programming I just want to print each place, 1 by 1.
Another question: I´m thinking of buying a development board to do this, what do you think about it? =) should I develop a driver using linux?
Thank you very much.
EDIT: here is my code that crash, and sry for newbie question =S
#include <stdio.h>
#include <iostream.h>

int main()
{
    int num[625];
    int x,y,count;
    do
    {
    printf("\n Inicializando... ");
    num[625]=num[count];
    count++;
    }
    while (num[count]!= 25);
    if (num[count]=25)
    {
        do
        {
        printf("\n Inicializando... ");
        num[625]=num[count];
        count++;
        } while (num[count]!= 25);

    }
    for (count=0;count<625;count++)
    printf (" %d",num[count]);

    system("pause");
    return(0);
}

A: This is probably NOT the actual answer to your question, but:
int num[625];
...
    num[625]=num[count];
...

Is storing something in an array position that doesn't actually exist. And C being a fairly permissive language, you are simply writing to something else immediately after the array - probably x. This is most likely NOT what you wanted to do.
Some further comments on the code here:
#include <stdio.h>
#include <iostream.h>

It's far from good to mix stdio.h with iostream (iostream.h is very OLD - if you are using a compiler that is standards compliant, then use iostream - however, since you also tagged this as C, rather than C++, I would suggest remove it altogether.
int main()
{
    int num[625];
    int x,y,count;
    do
    {
    printf("\n Inicializando... ");
    num[625]=num[count];

Note that aside from my comment above about addressing outside the array, num[count] has never been set - it has whatever value happens to be in that memory - which is quite possibly just about any value in the integer range.
    count++;
    }
    while (num[count]!= 25);

Since num[count] is not initialized, it may or may not ever be 25. Once count gets high enough, it will probably crash.
    if (num[count]=25)
    {
        do
        {
        printf("\n Inicializando... ");
        num[625]=num[count];
        count++;
        } while (num[count]!= 25);

    }
    for (count=0;count<625;count++)
    printf (" %d",num[count]);

I've never been a great fan of more than two, maybe three consecutive empty lines in a function.
    system("pause");
    return(0);
}

A: Try this algo.
Change NR By will It is the no of rows or columns.
#include<stdio.h>

#define NR 5

int main()
{
   int i,j,loop;
   for( loop=0; loop < NR*NR; loop++)
   {
      printf("Loop %d\n",loop);
      for(i=0;i< NR; i++)
      {
         for (j=0;j<NR;j++)
         {
            if ( loop == NR*j+i )  printf("X ");
            else                  printf("0 ");
         }
         printf("\n");
      }
      printf("\n");
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Заблокировать удаление первых 4 символов в editText То есть, дописывать можно, и стирать дописанный текст, а первые 4 символа должны оставаться.

A: *

*Согласно en-SO надо назначить слушатель событий ввода текста и в них проверять заданное условие:
final EditText edt = (EditText) findViewById(R.id.editText1);
edt.setText("http");
Selection.setSelection(edt.getText(), edt.getText().length());
edt.addTextChangedListener(new TextWatcher()
{
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count)
   {

   }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
        int after)
   {
        //Не тестировал, но, по идее, можно и тут следить за соблюдением условия
        if(count<4)
        {
            edt.setText("http");
            Selection.setSelection(edt.getText(), edt.getText().length());
        }
   }

    @Override
    public void afterTextChanged(Editable s)
    {
        if(!s.toString().startsWith("http"))
        {
            edt.setText("http://");
            Selection.setSelection(edt.getText(), edt.getText().length());
        }
    }
});

*Или можно перед EditText расположить TextView, содержащий нужные вам символы.


text:
Q: How to fix "MongoSocketException" to external MongoDB with Java? I'm trying to connect with my java spring boot server to my external mongoDB with this code:
MongoClientURI uri = new MongoClientURI(
                "mongodb+srv://username:password@integrationcourse-7bsmm.mongodb.net/test?retryWrites=true");

        MongoClient mongoClient = new MongoClient(uri);
        MongoDatabase database = mongoClient.getDatabase("course");
        MongoCollection<Document> collection = database.getCollection("UserEntitys");

And I'm getting this following error:
com.mongodb.MongoSocketException: integrationcourse-7bsmm.mongodb.net
    at com.mongodb.ServerAddress.getSocketAddresses(ServerAddress.java:211) ~[mongo-java-driver-3.11.0-beta2.jar:na]
    at com.mongodb.internal.connection.SocketStream.initializeSocket(SocketStream.java:75) ~[mongo-java-driver-3.11.0-beta2.jar:na]
    at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:65) ~[mongo-java-driver-3.11.0-beta2.jar:na]
    at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:128) ~[mongo-java-driver-3.11.0-beta2.jar:na]
    at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:117) ~[mongo-java-driver-3.11.0-beta2.jar:na]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_191]
Caused by: java.net.UnknownHostException: integrationcourse-7bsmm.mongodb.net
    at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method) ~[na:1.8.0_191]
    at java.net.InetAddress$2.lookupAllHostAddr(InetAddress.java:929) ~[na:1.8.0_191]
    at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1324) ~[na:1.8.0_191]
    at java.net.InetAddress.getAllByName0(InetAddress.java:1277) ~[na:1.8.0_191]
    at java.net.InetAddress.getAllByName(InetAddress.java:1193) ~[na:1.8.0_191]
    at java.net.InetAddress.getAllByName(InetAddress.java:1127) ~[na:1.8.0_191]
    at com.mongodb.ServerAddress.getSocketAddresses(ServerAddress.java:203) ~[mongo-java-driver-3.11.0-beta2.jar:na]
    ... 5 common frames omitted

A: used one older url sample from the atlas, pinged it and then connected to the DB. as suggested.


text:
Q: How to detect that a user click on "open" inside the play store to launch my app? How to detect that a user clicks on the button "open" inside the play store to launch my app (when the app is already installed) instead of launching directly the app by tapping its icon inside android main screen?

A: I recommend to use firebase, it is an example
<body>
  <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->

  <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
  <script src="/__/firebase/6.2.0/firebase-app.js"></script>

  <!-- Add Firebase products that you want to use -->
  <script src="/__/firebase/6.2.0/firebase-auth.js"></script>
  <script src="/__/firebase/6.2.0/firebase-firestore.js"></script>
</body>

The link is the next [https://firebase.google.com/docs/web/setup?hl=es-419][1]
[1]: https://firebase.google.com/docs/web/setup?hl=es-419, this link is showing how implement


text:
Q: NetBeans 7.1 building error : java.lang.UnsatisfiedLinkError libXtst.so.6: wrong ELF class: ELFCLASS64 I can't build my project using jdk 1.7.0 due to following error on NetBeans 7.1 whereas the same one works well on Eclipse with jdk 1.7.0. Does anyone know how can I resolve this issue ?
Output:
Exception in thread "main" java.lang.UnsatisfiedLinkError: /usr/lib/jvm/jdk.1.7.0/jre/lib/i386/xawt/libmawt.so:         libXtst.so.6: wrong ELF class: ELFCLASS64
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1928)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1825)
at java.lang.Runtime.load0(Runtime.java:792)
at java.lang.System.load(System.java:1059)
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1928)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1846)
at java.lang.Runtime.loadLibrary0(Runtime.java:845)
at java.lang.System.loadLibrary(System.java:1084)
at sun.security.action.LoadLibraryAction.run(LoadLibraryAction.java:67)
at sun.security.action.LoadLibraryAction.run(LoadLibraryAction.java:47)
at java.security.AccessController.doPrivileged(Native Method)
at java.awt.Toolkit.loadLibraries(Toolkit.java:1648)
at java.awt.Toolkit.<clinit>(Toolkit.java:1670)
at java.awt.Component.<clinit>(Component.java:595)
Java Result: 1

A: That's because you're running a 32bit JVM on a 64bit platform. Install the 64bit JDK and you're off. I have the same errors because I'm trying to run a 32bit JDK. :-)
I can only guess as to why Eclipse works. But it looks to me that this happens when trying to run something using Swing. Netbeans does. Eclipse however runs SWT; its own gui package.


text:
Q: scala msgpack decimal values Im using msgpack java with jackson serialization and its scala type conversions in a simple project. The msgpack is originally serialized in python and looks like price��5.0000� When i try to serialize in java or scala i get the following error
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of double out of VALUE_EMBEDDED_OBJECT token

This happens for any decimal type. Is there some trick to serializing decimal values in scala with msgpack?
These are the versions im using.
"org.msgpack" % "msgpack-core" % "0.8.13",
"org.msgpack" % "jackson-dataformat-msgpack" % "0.8.13",

"com.fasterxml.jackson.core" % "jackson-core" % "2.9.1",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.9.1",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.9.1",
"com.fasterxml.jackson.datatype" % "jackson-datatype-guava" % "2.9.1",
"com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.9.1",

A: You can get around this by writing a custom serializer for float values that also supports scientific notation strings from python using BigFloat. Returning new BigDecimal(<your string>) fixes this specific problem.


text:
Q: dispatch mouse out event when the mouse not out I created a tooltip class.
When the mouse over on MovieClip it enable and when it out it disable.
The movieclip containt some other movieclips.
My code is that:
to.addEventListener(MouseEvent.MOUSE_OVER, showTip);
to.addEventListener(MouseEvent.MOUSE_OUT, hideTip);
to.addEventListener(MouseEvent.MOUSE_MOVE, MoveTip);

and the functions is that:
private function showTip(evt: MouseEvent) {
        if (tip != null && !tip.visible) {
            tip.x = evt.stageX;
            tip.y = evt.stageY;
            tip.visible = true;
        }
    }

    private function hideTip(evt: MouseEvent) {
        if (tip != null && tip.visible) {
            tip.visible = false;
        }
    }

    private function MoveTip(evt: MouseEvent) {
        if (tip != null && tip.visible) {
            tip.x = evt.stageX;
            tip.y = evt.stageY;
        }

    }

Its work but sometimes the hideTip function and the showTip function enable in same time and the tip is flashing.

A: Apparently your tooltip obscures the underlying to movieclip, thus effectively making Flash to think that mouse is out of the to MC, triggering the mouse out listener. A possible solution is shifting the tip off the mouse cursor instead of displaying it right on top of the mouse position.
const offsetX:Number=4;
const offsetY:Number=4; // experiment with these
private function showTip(evt: MouseEvent) {
    if (tip != null && !tip.visible) {
        tip.x = evt.stageX+offsetX;
        tip.y = evt.stageY+offsetY;
        tip.visible = true;
    }
}

private function MoveTip(evt: MouseEvent) {
    if (tip != null && tip.visible) {
        tip.x = evt.stageX+offsetX;
        tip.y = evt.stageY+offsetY;
    }

}

A: Try to use
to.addEventListener(MouseEvent.ROLL_OVER, showTip);
to.addEventListener(MouseEvent.ROLL_OUT, hideTip);

That avoids the problem of dispatching the event, if the mouse changes e.g. between a letter and a transparancy in an area or between children of the same tooltip-target, which should completely have one tooltip. Sry for my english. Hope, it helps. Greetings

A: As @BotMaster and @Vesper suggested, the tip is displayed under the mouse, which causes the MouseEvent.MOUSE_OUT to fire.
To prevent this, do:
tip.mouseEnabled = false;
tip.mouseChildren = false;


text:
Q: Is it true that $ \sqrt{z^2-1} = i \sqrt{1-z^2} $? I have seen a lot of times in books or on the internet that$ \sqrt{z^2-1} = i \sqrt{1-z^2} $   and I don't understand why that is correct . In general it is not true that $ \sqrt{-z}=i  \sqrt {z}$ and I think that we use that to show the above.
I think if $(1-z^2)$ has argument in $(-π,0]$, then we have that $ \sqrt{-z}=i  \sqrt {z}$ but it's not always like that, for example if $z=-2+i$ then $ z^2=4-4i-1$ so $ 1-z^2=-2+4i $ and that one has not the argument that we want.
Thank you in advance!

A: The problem is the definition of the square root. Every complex number has 2 square roots (except 0), and we agree that if the number is real and positive, the sign $ \sqrt ?$ means to take the positive root. But when we're dealing with a general complex number z, we don't have one good way to define which of the roots will be $\sqrt z$. So for a general $z$, the eqation you wrote isn't well defined.
However, it is true that $\frac{\sqrt {1-z^2}}{\sqrt {z^2-1}}$ will always be $i$ or $-i$, no matter which root you choose for those numbers.


text:
Q: Who play important role in multicast of video on SharePoint Site For multicast of video on SharePoint Site, which of the following will play a important role?
[1] The Server hosting the SharePoint Site?
[2] The SharePoint Server itself
[3] The video player on the SharePoint Site
[4] The video itself.


text:
Q: Button with location.href doesn't work in Firefox I have a textbox for search and a button that redirects to given value of the textbox. It works well except for firefox 3, which ignores the function completely. Any ideas why and how to fix it? I have already tried window.location instead of location.href, but it again works well in all major browsers but firefox.
My code:
<%=Html.TextBox("search", Html.Encode(ViewData["search"])) %>
<input type="button" onclick="location.href='<%= Url.Content("~/Authorized/Accounts/0/1/") %>'+search.value" value="Search" />

EDIT
And here is the generated code:
<input id="search" name="search" type="text" value="" />
<input type="button" onclick="window.location='/Authorized/Accounts/0/1/'+search.value" value="Search" />

A: search.value is looking for a JavaScript variable called 'search', not your form field.
You should be using document.getElementById('search').value

A: <%=Html.TextBox("search", Html.Encode(ViewData["search"])) %>
<input type="button" onclick="location.href='<%= Url.Content("~/Authorized/Accounts/0/1/") %>'+document.getElementById('search').value;" value="Search" />

If you're using jQuery:
<%=Html.TextBox("search", Html.Encode(ViewData["search"])) %>
<input type="button" onclick="location.href='<%= Url.Content("~/Authorized/Accounts/0/1/") %>'+$("#search").val();" value="Search" />

A: I'm not sure why your code doesn't work in FF3, but I got it to work by adding the domain to the beginning of the URL and also by removing the leading slash.
So, if it's possible for you to either add the domain or use relative paths in that location, it should work. For example, the generated line might look like this:
<input type="button" onclick="window.location='http://www.example.com/Authorized/Accounts/0/1/'+search.value" value="Search" />


text:
Q: How can I rerender only one item in a flatlist? I have products with a star icon to add this product in wishlist. I map 10 list of products and each map has 3 products like:
(I Map it in Pagerview to swipe to the next products)
Products Component
const ListProducts = [
  {
    id: 1,
    products: [{
      product_id: 1,
      photos: [...]
    }]
  },
  {
    id: 2,
    products: [{
      product_id: 1,
      photos: [...]
    }]
  }
  {
    id: 3,
    products: [{
      product_id: 1,
      photos: [...]
    }]
  },
  {
    id: 4,
    products: [{
      product_id: 1,
      photos: [...]
    }]
  }
...
];

function isEq(prev, next) {
  if(prev.is_wishlist === next.is_wishlist) {
    return true;
  }
}

const Item = memo(({ id, photos, is_wishlist, onPress, onPressWishlist }) => {
  const findProductIdInWishList = is_wishlist.find((el => el.product_id === id));
  return (
    <Button style={s.imgBtn} onPress={() => onPress(id)}>
      <Button onPress={() => onPressWishlist(id)} style={s.starBtn}>
        <AntDesign name={findProductIdInWishList ? 'star' : 'staro'} size={20} color={globalStyles.globalColor} />
      </Button>
      <ImageSlider photos={photos} />
    </Button>
  )
  // @ts-ignore
}, isEq);

  const wishlist = useSelector((state) => state.WishList.wishlist);
  const dispatch = useDispatch();

  const renderItem: ListRenderItem<IProduct> = ({ item }) => (
    <Item
      id={item.id}
      photos={item.photos}
      is_wishlist={wishlist}
      onPressWishlist={handlePressWishList}
    />
  )

  const handlePressWishList = (product_id: string) => {
    dispatch(addAndRemoveProductToWishList({product_id}));
  };

List of Products component
Products Map:

      <PagerView onPageSelected={(e) => handleSetAllIndexes(e.nativeEvent.position)} style={s.container} initialPage={index}>
      {
        allProducts.map((el, i) => (
          <View style={s.viewsContainer} key={i}>
            { allIndex.includes(i) ? (
              <View style={s.viewsInnerContainer}>
                { /* products */ }
                <Products products={el.products as IProduct[]} total_price={el.total_price} product_name={el.packet_name} />
              </View>
              ) : (
              <View style={s.loadingContainer}>
                <Loader size={'large'} color='#fff' />
              </View>
              )
            }
          </View>)
        )
      }
      </PagerView>

if I click on star icon its dispatch and it goes fast but if I swipe to other products maybe to the last, then I press the star icon to dispatch then its a delay/lag you can see it
I dont add the full code because there are some snippets that has nothing to do with problem.
PS:
Video

A: I think there are a few issues in your code:
1. Wrong dependency list for useMemo.
In your Item component, you should pass the list of dependency, rather than a compare function:
const Item = memo(({ id, photos, is_wishlist, onPress, onPressWishlist }) => {
  ...
  // @ts-ignore
}, isEq);  // <- this is wrong

// Instead, you should do this:
}, [is_wishlist]);  // <- this is correct, if you only want to update Item component when `is_wishlist` is changed

2. Never use index as key if item can be reordered
In your products maps component, you are doing:
allProducts.map((el, i) => (
  <View style={s.viewsContainer} key={i}>

You should pass id instead, so React will not re-render all items when you insert a new item at the beginning or in the middle:
<View style={s.viewsContainer} key={el.id}>

3. Passing wishlist to all Items, however, wishlist will be updated whenever user click star button on any item.
This causes all Item to re-generate memoized component, because wishlist is changed.
What you want to do here is only passing essential data to Item, which is inWishList (or findProductIdInWishList in your code), which only get changed for affected item:
const renderItem: ListRenderItem<IProduct> = ({ item }) => {
  const inWishList= wishlist.find((el => el.product_id === id));
  return (
    <Item
      id={item.id}
      photos={item.photos}
      inWishList={inWishList}
      onPressWishlist={handlePressWishList}
    />
  )
}

A: I am going to edit my answer instead of comment. Before my code, let me explain first. In your current code, whenever 'allProducts' changes, everything will re-render. Whenever 'allIndex' changes, everything will re-render too. The longer the list, the more lag it will be.
Can you try 'useCallback' in this case?
const renderItem = React.useCallback((el, i) => (
  <View style={s.viewsContainer} key={i}>
      {allIndex.includes(i) ? (
        <View style={s.viewsInnerContainer}>
          <Products />
        </View>
      ) : (
        <Loading />
      )}
    </View>
),[allIndex])

{allProducts.map(renderItem)}

Now, renderItem will re-render when 'allIndex' changes. Instead of 'PagerView', I still recommend 'FlatList' with 'horizontal={true}' and 'some styles'. If still wanna use 'PagerView', how about 'Lazy' components? 'Lazy components' does not render the components before they came into user view. So, before they are seen, they do not take part in re-redner.

A: The issue is connected to a way how you edit your data to hold the new value. It looks like the act of adding an item to a wishlist causes all the previous items to re-render.
Therefore the first one works without an issue, but the last one takes a while as it needs to re-render all the other items before.
I would start by changing the key from index to an actual ID of a product block since that could prevent the other "pages" from re-rendering.
If that fails you will probably need to take this block of code into a workshop and check for useless re-renders.


text:
Q: Programmatically getting the per-core CPU load for a Windows system I am trying to programmatically determine what the idle/running break-down is for the CPU cores.
In Linux, I use /proc/stat for this, which gives me cycle counts for cycles spent in:

*

*user: normal processes executing in user mode

*nice: niced processes executing in user mode

*system: processes executing in kernel mode

*idle: twiddling thumbs

*iowait: waiting for I/O to complete

*irq: servicing interrupts

*softirq: servicing softirqs

Please note: I am getting system-wide numbers, not the cpu-usage for a specific process!
Now, I want to do the same, but in C, for a Windows system.
UPDATE
I've been able to find an aggregate statistic, so not per core: GetSystemTimes() which will return a value for idle, kernel and user cycles. What really confused me at first, is that the kernel cycles include idle cycles.


text:
Q: ColdFusion Code as failing on if condition Working with cfscript code in ColdFusion, The following seems correct to me, if client_discount is either 0 or NULL, just do not generate the UniqueKey, use existing else use new one. But it does work somehow, I am not sure what I am missing here, trying different cflib UDF's also:
Here is my code:
f = structnew();
f.discountoffered = '#arguments.structform.client_discount#';
writedump(arguments);
result = structFindKeyWithValue(f,f.discountoffered,"0","ALL");
writedump(result);

if((arguments.structform.client_discount EQ 0)
    OR (arguments.structform.client_discount NEQ "")) {
    f.orderunique = generateRandomKey();
}
else {
   f.orderunique = '#arguments.structform.orderunique#';
}

A: NULL is kind of wonky in ColdFusion.
I would handle this by paraming the value so it gets a value I decide if it does not exist.
Add this code under f = structNew() - or at the beginning of the function, does not really matter.
param name="arguments.structForm" default="#structNew()#;
param name="arguments.structForm.client_discount" default="0";

This way if client_discount is not present, it is set to 0 - the first line is to make sure that structform exists in arguments and if not, sets it to an empty struct.
Then your if statement need only check if it is 0.
if( arguments.structForm.client_discount == 0 ){
    f.orderunique = generateRandomKey();
}
else{
    f.orderunique = arguments.structform.orderunique;
}

Of course...you would need to verify that arguments.structForm.orderunique exists before using it.

A: I think that's what you are trying to do
<cfscript>
f = structnew();
    if(not isnull(arguments.structform.client_discount)){
      f.discountoffered = '#arguments.structform.client_discount#';
      result = structFindKeyWithValue(f,f.discountoffered,"0","ALL");
       if((arguments.structform.client_discount EQ 0))
        f.orderunique = generateRandomKey();
         else
        f.orderunique = '#arguments.structform.orderunique#';
    }
else {
     f.orderunique = '#arguments.structform.orderunique#';
}
</cfscript>


text:
Q: Why does the command mv return the message mv: cannot move Device or resource busy on Linux? I was attempting to move files from one directory to another and was displayed the following message although the files were moved. Why does display the "error" and what does it mean? When does it occur? The directories are on the same device and partition. The device runs off Ubuntu 12.04 LTS
Error
*mv: cannot move `.' to `../new_media/press/.': Device or resource busy*

A: From the rename(2) man page:
   EBUSY  The  rename fails because oldpath or newpath is a directory that
          is in use by some process (perhaps as current working directory,
          or  as root directory, or because it was open for reading) or is
          in use by the system (for example as  mount  point),  while  the
          system considers this an error.  (Note that there is no require‐
          ment to return EBUSY in such cases — there is nothing wrong with
          doing  the  rename anyway — but it is allowed to return EBUSY if
          the system cannot otherwise handle such situations.)

A: Some process is using the file/s. You can find what files are open by what processes using the command 'lsof' (list open files). This will return a lot of open files. Once you've found the process, you could try killing it.
Or restarting the computer may be easier if that is an option.


text:
Q: Code on Func and Action http://simpleprogrammer.com/2010/09/24/explaining-what-action-and-func-are/
The above code explains in simple terms about Action  and Func.
Still I am not getting what it is for 100%. Or not able to make the code work for me.
public void SteamVegetable(Vegetable vegetable, int timeInMinutes)
{
    CookVegetable(vegetable, Steam, timeInMinutes);
}

public void FryVegetable(Vegetable vegetable, int timeInMinutes)
{
    CookVegetable(vegetable, Fry, timeInMinutes);
}

public void BakeVegetable(Vegetable vegetable, int timeInMinutes)
{
    CookVegetable(vegetable, Bake, timeInMinutes);
}

public void CookVegetable(Vegetable vegetable,
   Action<Vegetable, CookingTime> cookingAction,
   int timeInMinutes)
{
    Clean(vegetable);
    cookingAction(vegetable, Minutes.Is(timeInMinutes));
    Serve(vegetable);
}

Can someone help me to convert the code from vegetable to numbers and Steam --> Addition, Fry --> Multiplication, Bake --> subtraction when two operands are passed to it.
When I see the code working I can understand it better.

A: I might be wrong in understanding what you want, but I'll try to answer it. Note, that I omit many complex things in example, like I would use generics instead of plain int values, but this will just create redundant complexity in the example.
In example below I just define high-order function, which takes two int values, function, that transforms two values into string (i.e. encapsulate some behavior) and them embrace this result into enclosing and opening tags, one of which is passed in. Note, that I assume you are familiar with lambda notation in C#.
ApplyAndPrettyPrint(100, 3, "summ of 100 and 3 is equal to: ", (x,y) => (x*y).ToString("N0"));
ApplyAndPrettyPrint(100, 3, "100 to power 3 is:  ", (x,y) => (Math.Pow(x,y)).ToString("N0"));
ApplyAndPrettyPrint(2, 33, "2 * root of 33 is:  ", (x,y) => (x * Math.Sqrt(y)).ToString("N0"));

public void ApplyAndPrettyPrint( int firstNumber, int secondNumber, string startTag, Func<int, int, string> evaludationFunction)
{
    string result = startTag;
    result += evaludationFunction(firstNumber, secondNumber);
    result += ";";
    Console.WriteLine (result);
}

So that Func here is used like a box, with two integers as input and one string as output.
Second example shows how we can pass Action into method, that will be evaluated over some array of numbers. Again, I omit details of IEnumerable interfaces and generics.
int[] numbers = new []{ 1, 2, 4, 5, 6, 7 };
ApplyForEach(numbers, (x) => Console.WriteLine ("square of {0} is {1}", x, x*x));

public void ApplyForEach(int[] numbers, Action<int> someFunction)
{
    foreach (var number in numbers)
    {
        someFunction(number);
    }
}

The result will just print squares of integers with some descriptive chars. In other word Action is delegate with no outputs. You can think of them as box with some inputs, but with no outputs at all.
Hope that this will do the trick for your understanding. The bottom line is that the only difference between delegate types of Action and Func is the semantics of the last generic type: in Func it is the returning value, in Action returning value is void, so last generic type just goes to input parameter.
If you find this topic somewhat difficult, Jon Skeet describes delegates within Chapter 5 "Fast-tracked delegates" in his marvelous book "C# in Depth"

A: In the example you provided, Fry, Steam, and Bake are probably supposed to be methods.
Basically, Actions and Funcs let you pass a chunk of code into a method, then execute that chunk of code.
So, you could do
public void Foo(Action<int> actionToPerform, int someInt)
{
    actionToPerform(someInt);
}

Then, you could use the Foo method with any "chunk of code" that takes an integer.
So,
public void Bar()
{
     Action<int> writeToConsole = i =>  { Console.WriteLine(i); }
     Action<int> writeToSomeLogger = i => { Logger.WriteLog(i); }
     Foo(writeToConsole, 10);
     Foo(writeToSomeLogger, 100);
}

A: I'm going to throw my example in.. I tried to make it simple, so hopefully this helps.
Take this for example:
class MathClass {
    public int Add(int number1, int number2) {
        return DoSomeMathOperation(number1, number2, theAddingIsActuallyDoneHere); // The method "theAddingIsActuallyDoneHere" below is what gets called.
    }

    private int theAddingIsActuallyDoneHere(int number1, int number2) {
        return number1 + number2;
    }

    public int Multiply(int number1, int number2) {
        return DoSomeMathOperation(number1, number2, theMultiplicationIsDoneHere); // The method "theMultiplicationIsDoneHere" is what gets called.
    }

    private int theMultiplicationIsDoneHere(int number1, int number2) {
        return number1 * number2;
    }

    public int DoSomeMathOperation(int number1, int number2, Func<int, int, int> mathOperationFunc) {
        return mathOperationFunc(number1, number2); // This is where you call the method passed in above.
    }
}

The above code, can be used like this:
MathClass mathClass = new MathClass();

Console.WriteLine(mathClass.Add(5, 10)); // displays 15
Console.WriteLine(mathClass.Multiply(5, 5)); // displays 25

Imagine though, that you required a subtraction method. You can create one, via the DoSomeMathOperation function, which expects a Func<int, int, int>, which is a function that "takes 2 integer parameters and returns an integer". This would be implemented as follows:
Console.WriteLine(mathClass.DoSomeMathOperation(100, 50, (num1, num2) => num1 - num2)); // displays "50"

In the above code, you're passing the numbers 100 and 50 into the DoSomeMathOperation method, and those two parameters are being passed into the Func<int, int, int>. The result is then returned.
..hopefully that makes sense..


text:
Q: What are XSAVE and /dev/xvda1 So I logged into a new Amazon EC2 instance created with one of their new "standard" AMI's. Instead of seeing /dev/sda1 I see /dev/xvda1 . This relates to Xen somehow.
Here's what I can find that mentions this:
http://www.ioncannon.net/system-administration/1290/how-to-build-compile-a-custom-linux-kernel-for-ec2/
It says: "Apply the following patch to disable XSAVE". (someone must have done that before building the standard AMI)
Then it says: "Note that the root device here is /dev/xvda1 instead of /dev/sda1. This is caused by the XSAVE patch."
And finally it says: "Note that the devices here are /dev/sda1 and not /dev/xvda1. That is a little confusing but the AWS system doesn't see the devices in the same way your AMI will once it is booted."
Yes, it is kind of confusing and I would like to understand it.
Googling XSAVE and XVDA1 are not helpful at all.

A: XSAVE and /dev/xvda1 have nothing to do with each other. That link is incorrect.
XSAVE is a CPU feature that Xen should not present to a kernel running in a VM. See https://partner-bugzilla.redhat.com/show_bug.cgi?id=524719
When configuring Xen you present a block device to the guest VM (domU, "AMI"). By convention (was a requirement in the past) they are prefixed with "xvd" (Xen virtual disk). In the host OS (dom0, "AWS system") this block device will be called something different. In the EC2 case it is a SCSI-like disc hence the "sd" prefix.


text:
Q: sed or grep or awk to match very very long lines more file
param1=" 1,deerfntjefnerjfntrjgntrjnvgrvgrtbvggfrjbntrrfr4fvfrfftrjgtrignmtignmtyightygjn      2,3,4,5,6,7,8,
rfcmckmfdkckemdio8u548384omxc,mor0ckofcmineucfhcbdjcnedjcnywedpeodl40fcrcmkedmrikmckffmcrffmrfrifmtrifmrifvysdfn"
need to match the content of $param1 in the file
but its not work for example
sed -n "/$param1/p" file
or any grep $param1 file etc...
any other solutions? maybe with perl?

A: Hard to help without the exact script you are running, but one point to check:
The value for "param1" that you posted contains asterisk characters ("*"). These have special meaning to sed and grep (and perl, and generally in any regular expression). To match these as literal characters, you usually need to "escape" them by prepending a backslash.
So instead of "aa*b" you'd need "aa*b". Try this first to see if it helps.
Caveat: The shell will also process a \, so when using it as a parameter value put the value into '', as:
param1='basldafsd\*asdfsadf'

The '' will protect special chars from the shell.


text:
Q: How do I convert text block to code block? I have to create code snippets in UI (like in StackOverflow/bootstrap etc.) where the data is coming from the database.
Suppose my code is:
class test {
  public static void main(String args[]) {
    System.out.println("Hello");
  }
}

I am sending this piece of code exactly like this (with proper tabs and enter) but when I render this in view it becomes a single line. I saw that the data gets stores as a single line in the database.
Is there any way to do this in Angular? I have tried using pre but it can't understand where to break line.


text:
Q: How to get author of another bot's slash command? discord py I need to my bot get id of user who used slash command of another (not my) bot: this
I have on_message, which checks if a bot message was sent on an available channel, but when I use print(message.author.id) it doesn't show the author of the command, only the bot id, additionally the message type, it shows me as default, doesn't respond
@client.event
async def on_message(message):
    if (message.channel.id == 926874863099084830):
        print(message)

<Message id=1027876766963994664 channel=<TextChannel id=926874863099084830 name='┆┆bump' position=7 nsfw=False news=False category_id=880095072794849340> type=<MessageType.default: 0> author=<Member id=302050872383242240 name='DISBOARD' discriminator='2760' bot=True nick=None guild=<Guild id=772531463051804692 name='Imperium RPG' shard_id=None chunked=True member_count=629>> flags=<MessageFlags value=0>>

A: discord.Message.interaction may be a discord.MessageInteraction object. Which has a user attribute.
if message.interaction:
    print(message.interaction.user)


text:
Q: CakePHP Parsing data from file and adding to database I have a file that I wish to parse and add to the database.
The way I wish to do it is this:

*

*The user uploads the file

*File is parsed

*The users are given the parsed data and selects what they want to keep

*They submit

(More detailed explanation follows)
I have a film script file that I wish to parse and enter scenes and their respective characters and props. I have already managed to parse this file into an array using php.
What I want to do now is to

*

*prompt the user with the various scenes and its contents

*allow the user to fix / modify the data before submitting it into the database.

The thing is that the script file has more than one scene in it, so I am unsure how to handle the data-entry aspect of this problem.
Are there any "best practices" for these kinds of data entries?
(if I didn't explain something in enough detail, please tell me and I'll update the question).

A: I would simply parse the file and save it as it is to the database. Something like Script hasMany Scenes. Let them select their script and simply paginate the Scene records and let them delete them.
Is there an urgent need to not save them all after import? Another downside of your approach is that if the browser crashes or the user closes it he has to start over again because you just kept the data in memory but not persistant.
If you want to rely on your approach you'll have to work with the data coming back from the form and simply remove the key from the form data.
Like doing this in a foreach running over the data structure
if ($data['Scene][$key]['delete'] == 1) { unset($data['Scene'][$key]); }


text:
Q: How can I select data between an hour range without using extract? I'm trying to select data between an hour range, without using extract to be able to use the indexes in the table. I do the query like this:
SELECT  *
FROM    activities
WHERE   "dateParam"::timestamp >= '21:00:00'::timestamp
AND     "dateParam"::timestamp <= '23:00:00'::timestamp;

But I get an 22007 state and it doesnt work, how could I be able to do it?

A: Try:
SELECT  *
FROM    activities
WHERE   "dateParam"::timestamp >= current_date + '21:00:00'::time
AND     "dateParam"::timestamp <= current_date + '23:00:00'::time;

A timestamp needs a date portion so add it.


text:
Q: how to add missing "Wireless Network (IEEE 802.11) Policies" to group policy I have a laptop with "Windows 7 Professional" installed.  It is going to be used by someone for whom I must carefully control interned access.  For many reasons, I want to do this using group policy editor.  (Please don't say "you shouldn't be trying to control access", or "just do it this other way" - I have omitted many many pertinent details for reasons of privacy, and without knowing and understanding all the details, you cannot judge.)
In particular, I need to set up group policy in "Wireless Network (IEEE 802.11) Policies" (under "Security Settings") for the user.
However, when I run the group policy editor, there is no "Wireless Network (IEEE 802.11) Policies" node.  Everything I can find on the web either assumes the node is there, or is geared towards and enterprise environment with a DC.
How can I add this policy to the "Security Settings" in the group policy editor?  Thanks.


text:
Q: How to connect this 5 pin audio jack? I have this 5 pin 3.5mm Stereo Jack Socket, and I don't know what pin is the left, right and the ground.

Can anyone make arrows on this picture showing every pin label??
Sorry just a newbie :/

A: I think this is what you are looking for.


text:
Q: Jsmooth icon looks bad I'm converting an executable jar to an exe with JSmooth. I'm setting an Icon in png for the application. It loads and it's show OK at Jsmooth. Then I convert to exe, and it works, but the icon looks very bad, pixelated.
My icon is a 64x64 png with transparent background. Where is the problem?

A: Looks like Jsmooth autoscale to 32x32 and reduce colors to 256, so it's preferable to do that with external software, or give Jsmooth a proper ico file.
Extracted from Jsmooth user manual:


text:
Q: Can you use Orchard CMS with Entity Framework 5 instead of NHibernate? Can you use Orchard CMS with Entity Framework 5 instead of NHibernate?
I'm writing an MVC 4 Code First app and don't want to have to learn NHibernate - I would like all my projects to be consistent and use Entity Framework 5+
Thanks.

A: No. That is not possible, sorry.

A: you don't have to know how nhibernate works, using the Orchard content manager and standard Linq is enough in almost all scenario's. We use entity framework in our other projects. And the  migrations in Orchard are simple but powerfull. Think about it.


text:
Q: How can I apply a style to elements of a submatrix of a tikz matrix? I'm trying to apply a style for a submatrix of a matrix and ended up by passing arguments through two .list-handlers. Things don't work as I expected, again I'm just able to set either rows or columns but not both.
What's the problem? Do you have another idea?
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix,positioning}

\tikzset{
  rows/.style 2 args={
    @/.style={row ##1 column #2/.style={nodes={rectangle,draw=black}}},
    @/.list={#1}
  },
  box/.style 2 args={
    @/.style={rows={#1}{##1}},
    @/.list={#2}
  }
}
\tikzset{square matrix/.style={
    matrix of nodes,
    column sep=-\pgflinewidth, row sep=-\pgflinewidth,
    nodes={
      minimum height=#1,
      anchor=center,
      text width=#1,
      align=center,
      inner sep=0pt
    },
  },
  square matrix/.default=1.2cm
}

\begin{document}

\begin{tikzpicture}[]
\matrix[square matrix,
  box={1,...,3}{3,2} % apply the style to cells {1,3},{2,3},{3,3},{1,2},{2,2},{3,2}
]
{
   & x & x &   &   &   \\
   &   & x &   & x &   \\
 x & x & x & x & x &   \\
   &   & x &   &   &   \\
};
\end{tikzpicture}
\end{document}

A: Your code is almost ok. You have just to not use the same style @ in rows and box.
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix,positioning}

\tikzset{
  rows/.style 2 args={
    sub@rows/.style={row ##1 column #2/.style={nodes={rectangle,draw=red}}},
    sub@rows/.list={#1}
  },
  box/.style 2 args={
    sub@box/.style={rows={#1}{##1}},
    sub@box/.list={#2}
  }
}
\tikzset{square matrix/.style={
    matrix of nodes,nodes in empty cells,
    column sep=-\pgflinewidth, row sep=-\pgflinewidth,
    nodes={
      minimum height=#1,
      anchor=center,
      text width=#1,
      align=center,
      inner sep=0pt
    },
  },
  square matrix/.default=1.2cm
}

\begin{document}

\begin{tikzpicture}[]
\matrix[square matrix,
  box={1,...,3}{3,2} % apply the style to cells {1,3},{2,3},{3,3},{1,2},{2,2},{3,2}
]
{
   & x & x &   &   &   \\
   &   & x &   & x &   \\
 x & x & x & x & x &   \\
   &   & x &   &   &   \\
};
\end{tikzpicture}
\end{document}


text:
Q: Angular 6 and DotNetNuke (DNN) I am trying to integrate an angular app into a DotNetNuke (DNN) SPA module.I know angular but I am a beginner with DNN, I have Chris Hammond's DDN templates installed and I know how to create and install a DNN module, but I can't for the life of me figure out how to integrate an angular app into a DNN module.

A: You can find a "scafolding angular project" here:
https://github.com/OPSI-srl/DNN-Angular-6-7-CLI
And DNN module where to deploy your project:
SPA DNN9: https://github.com/OPSI-srl/DNN-9.x-SPA-and-Angular-6-7
ASCX for all DNN: https://github.com/OPSI-srl/DNN-7.x-8.x-9.x-and-Angular-6-7
all works with dnn webapi and security.
I used these projects with my customers.
Let me know
p.s. I'm not using Chris Hammond's DDN templates, it can be my next work. Let me know which version of template you are using.
thanks
Matteo


text:
Q: How can I safely write a disk image to a memory card? I routinely copy disk images to SD cards for use on a Raspberry Pi.  The usual way I do this is by dd if=/tmp/filesystem.img of=/dev/sdb, which is only a minor typo away from over-writing my computer's boot drive on /dev/sda.
Is there a safer way to do this, eg. by removing permission to do raw writes to the boot drive?

A: I think simplest solution is not to have do it as root and force SD card to always get the same letter. You can use udev to achieve that.
First use udevinfo to get enough atributes to uniquely identify your card (or cards) then create rule that will assign specific letter and access rights to device created by kernel for your SD card. One of the first links from google
Now if for whatever reason this fails write wrapper script for dd that will check if device's attributes match SD card and only if they do run dd.

A: There's nothing stopping you using a script with the target device built in to it.
#!/bin/bash
#
# Usage:  <script>  <image>
#
img="$1"
dev=/dev/sdb
echo -n "Copy image $img to $dev..."
sleep 5

echo -n " writing..."
cat "$img" >"$dev"
ss=$?

echo " done"
exit $ss

Put that in your $PATH somewhere and ensure it's executable.


text: Q: How to find the influence function of $\int_{[0,t]}(1-F_\_)^{-1}dF$,i.e., cumulative hazard function The common strategy is to replace $F$ with $(1-t)F+t\delta_x$ and then expand the integral. However, I am not sure how to deal with $F_\_$. It seems different from $F$.


text:
Q: Plotting a subset of sequential (time series) data in R I have a data frame similar to the one below, called df. I want to  plot subsets of this data, from say May 2012 to June 2014. I had been using the plot function to plot the entire data frame, however, when I split it up into subsets of the plot I get the same plot no matter what portion of the data I select.
     Jan       Feb       Mar       Apr       May       Jun       Jul       Aug       Sep       Oct       Nov       Dec
2011        NA        NA        NA        NA        NA        NA 13.724575 13.670017 13.782099 13.675788 13.442914 13.279969
2012 13.114463 13.021268 12.999545 12.990171 12.898018 12.611495 12.311641 12.126345 11.974871 12.019042 12.163618 12.304660
2013 12.374017 12.365795 12.323280 12.377747 12.462203 12.630298 12.780495 12.848942 12.806210 12.860463 12.838953 12.608965
2014 12.616257 12.720611 12.841626 12.897939 13.008535 13.136377 13.159393 13.290928 13.495218 13.636360 13.797778 13.827273
2015 13.662063 13.527596 13.568430 13.782818 13.889276 13.971303 14.181846 14.329937 14.385533 14.289386 14.222535 14.384618
2016 14.516674 14.759385 14.951384 14.763781 14.536779 13.978265 12.888989 11.612033 10.362592 9.205528  8.649027  8.662219
2017  8.614229  8.446361  8.239606  8.286693  8.498938  8.972903        NA        NA        NA        NA        NA        NA

My current code looks similar to below (Stripped out the non-essentials, like x and y labels).
dates <- seq(as.Date("2011-01-01"), by = "months", length = 84)
plot(dates, df, type = "l")

How can I modify this to plot only certain sections?
I would be OK with switching to ggplot2 too, but that seemed to give me weird results so I stuck with plot() (perhaps that's because it's a time series data frame? I'm not sure).

A: You need to get a subset of your data. Also, I would convert the data frame form wide to long format which is much easier to work with, specially for plotting/visualization purposes;
#long format with many rows instead of many columns
library(reshape2)
long <- melt(df, id.vars = c("Year"))

#add a column with actual dates instead year and month in different columns
long$date <- as.Date(with(long,paste(variable,"15",Year,sep = "-")), "%b-%d-%Y")

#take the subset of the data for May 2012 to June 2014
Date1 <- as.Date("2012-05-01", "%Y-%m-%d")
Date2 <- as.Date("2014-06-30", "%Y-%m-%d")
subdf <- long[long$date < Date2 & long$date > Date1,]

#use ggplot2 as it provides us nice labels and theme for timeseries by default
library(ggplot2)
ggplot(data=subdf, aes(date,value)) + geom_line()

Data:
df <- structure(list(Year = 2011:2017, Jan = c(NA, 13.114463, 12.374017,
      12.616257, 13.662063, 14.516674, 8.614229), Feb = c(NA, 13.021268,
      12.365795, 12.720611, 13.527596, 14.759385, 8.446361), Mar = c(NA,
      12.999545, 12.32328, 12.841626, 13.56843, 14.951384, 8.239606
      ), Apr = c(NA, 12.990171, 12.377747, 12.897939, 13.782818, 14.763781,
      8.286693), May = c(NA, 12.898018, 12.462203, 13.008535, 13.889276,
      14.536779, 8.498938), Jun = c(NA, 12.611495, 12.630298, 13.136377,
      13.971303, 13.978265, 8.972903), Jul = c(13.724575, 12.311641,
      12.780495, 13.159393, 14.181846, 12.888989, NA), Aug = c(13.670017,
      12.126345, 12.848942, 13.290928, 14.329937, 11.612033, NA), Sep = c(13.782099,
      11.974871, 12.80621, 13.495218, 14.385533, 10.362592, NA), Oct = c(13.675788,
      12.019042, 12.860463, 13.63636, 14.289386, 9.205528, NA), Nov = c(13.442914,
      12.163618, 12.838953, 13.797778, 14.222535, 8.649027, NA), Dec = c(13.279969,
      12.30466, 12.608965, 13.827273, 14.384618, 8.662219, NA)), .Names = c("Year",
      "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
      "Oct", "Nov", "Dec"), class = "data.frame", row.names = c(NA, -7L))

Reshaped data to long format:
head(long)

#   Year variable    value       date
# 1 2011      Jan       NA 2011-01-15
# 2 2012      Jan 13.11446 2012-01-15
# 3 2013      Jan 12.37402 2013-01-15
# 4 2014      Jan 12.61626 2014-01-15
# 5 2015      Jan 13.66206 2015-01-15
# 6 2016      Jan 14.51667 2016-01-15


text:
Q: tikz overlay pictures horizontal positioning I think I have a problem about how the box created by tikzpicture is positioned with respect the rest of the text. I have read Positioning TikZ pictures and I think I have understood how the vertical alignment works, but I can't find an equivalent for the horizontal one.
Consider the MWE:
\documentclass{report}
\usepackage{tikz}
\def\go[#1]{% does not work with current bounding box
    \tikz[#1]{
        \draw   (0,0) node (sw) {sw} --
                (1,0) node (se) {se} --
                (1,1) node (ne) {ne} --
                (0,1) node (nw) {nw} -- cycle;}
        \hspace*{2cm}
    }
\begin{document}

A\go[overlay, red, baseline=(sw)]
B\go[overlay, blue, baseline=(se)]
C\go[overlay, green, baseline=(ne)]
D\go[overlay, black,  baseline=(nw)]

\vspace{2cm}
A\go[overlay, red, baseline=(current bounding box.south west)]
B\go[overlay, blue, baseline=(current bounding box.south east)]
C\go[overlay, green, baseline=(current bounding box.north east)]
D\go[overlay, black,  baseline=(current bounding box.north west)]

\end{document}

Which gives:

I have two doubts here:

*

*why the two lines are not the same?

*I am trying to have the squares with the east reference (blue and green) before the letter B and C (given that the overlay figure has no size, I want it to extend before the insertion point). I understand that this is expected and correct for the baseline case (it just shifts the box vertically); but... is there an equivalent for the horizontal case?
To be more specific: I can move the figure with \llap or \rlap or similar tricks, but I was wondering: when tikz smashes the size of the picture to zero, it is like it is collapsing it to a point; is there a way to decide where this point is? I tried anchor too, but it works for the objects in the picture, not the picture itself.

A: This might be a solution for you.  I'm not sure how to achieve the effect you want using just one TikZ picture.  So, you might get the idea to nest the TikZ pictures.  But if you do a search on nesting tikzpictures, you find plenty of opinion expressed that this is not a good idea.  So instead of directly nesting the TikZ pictures, we smuggle the one in to the other by means of a \usebox construction.
I'm not sure what you want to do with the structures you're creating, so this may not be a solution that will work for you, but here it goes...
\documentclass{report}
\usepackage{tikz}

\def\go[#1]{% does not work with current bounding box
    \tikz[#1]{
        \draw   (0,0) node (sw) {sw} --
                (1,0) node (se) {se} --
                (1,1) node (ne) {ne} --
                (0,1) node (nw) {nw} -- cycle;
        }}

\makeatletter

\def\ae@anchor@xoffset{0pt}
\def\ae@anchor@yoffset{0pt}
%% "content"    will hold the smuggled in tikz picture.  It should be wrapped in
%%              brackets to prevent the key parser from misinterpreting comma.
%%
%% "anchor"     will specify how to anchor the node for the second tikz picture
%%
%% "x|yoffset"  will allow you to fine tune the placement of the content
\pgfkeys{/ae/anchor/picture/.cd,
  content/.store in=\ae@anchor@picture@content,
  anchor/.code={\def\ae@anchor@picture@node@anchor{node [outer sep=0pt,inner sep=0pt,anchor=#1]}},
  xoffset/.store in=\ae@anchor@xoffset,
  yoffset/.store in=\ae@anchor@yoffset,
}

\newsavebox\aebox
%% everything will be placed in a group to localize values to
%% current instance.
\newcommand\aeanchorpicture[1]{%%
  \bgroup
    \pgfkeys{/ae/anchor/picture/.cd,#1}%%
    \begin{lrbox}\aebox
      \ae@anchor@picture@content
    \end{lrbox}%%
    \tikz[remember picture,overlay]
      \path (0,0) -- ++(\ae@anchor@xoffset,\ae@anchor@yoffset)
      \ae@anchor@picture@node@anchor {\usebox\aebox};%%
  \egroup
  \hspace*{2cm}%%
}

\makeatother

\begin{document}

A\aeanchorpicture{content={\go[red]},   anchor=south west, xoffset=-2pt,yoffset=-2pt}%%
B\aeanchorpicture{content={\go[blue]},  anchor=south east}%%
C\aeanchorpicture{content={\go[green]}, anchor=north east}%%
D\aeanchorpicture{content={\go[black]}, anchor=north west}%%

\end{document}


text:
Q: Redirect to the previous page previous page after running login script (different pages run same script, but want to redirect to the right one) sorry if this is a simple question, but I am new to php!
I have a "header" file which is the nav bar for all of the pages in my website, through the require statement. A part of this nav bar is set to either show login/ logout buttons dependent on whether the user is logged in. When the user submits the form, the data is sent to a php file, and if there's an error, the request is sent back (with fields completed), or there's a header to the index page.
The issue is, I want the header to be to the previous page (not the required header file, but the main webpage. I thought of putting something inside the php tags where the "require" is, but that didn't seem to work.
Does anyone have any ideas? I will only send the relevant areas of code as these are big pages!
content-header.php
<DOCTYPE! html style="scroll-behavious: smooth;">

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <?php

        if(basename(__FILE__).PHP_EOL == '/J277_01/1.1.1/J277_performance') {
            echo '<title>1.1.1</title>';
          } else {
            echo "<title>Learn Don't 4Get</title>";
          };

        ?>

        <link rel="stylesheet" href="../../../css/reset.css">
        <link rel="stylesheet" href="../../../css/demo.css">
        <link rel="stylesheet" href="../../../css/index.css">
        <link rel="stylesheet" href="../../../css/header.css">
        <link href="../../../CSS/course.css?ts=<?=time()?>" rel="stylesheet" type="text/css">

        <link href="https://fonts.googleapis.com/css?family=Play" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css2?family=Exo:wght@700&display=swap" rel="stylesheet">

About

News

Resources

Specification

Contact

                    <?php
                    session_start();
                    if (!isset($_SESSION['id'])) {
                        echo '

Sign in

Sign up
';
                    } else{
                        echo'

<form action="includes/logout.inc.php" method="post"><button class="cd-main-nav__item cd-main-nav__item--logout" type="submit" name="course">Log Out</button></form>
';
                    }

                    ?>

Sign in

Create an Account

                <form class="cd-signin-modal__form" id="login-form" action="../../../includes/login.inc.php" method="post">

                        E-mail
                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border mailuidfield" id="signin-email" type="email" name="mailuid" placeholder="Username or E-mail">
                        Error message here!

                        Password
                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border pwdfield" id="signin-password" type="text" name="pwd" placeholder="Password">
                        Hide
                        Error message here!

                        <input type="checkbox" id="remember-me" checked class="cd-signin-modal__input ">
                        Remember me

                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width" name="login-submit" type="submit" value="Login">

                </form>

Forgot your password?

                <form class="cd-signin-modal__form" id="signup-form" action="../../../includes/signup.inc.php" method="post">

                        First Name
                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border" id="signup-first" type="text" name="first" placeholder="First Name">
                        Error message here!

                        Last Name
                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border" id="signup-last" type="text" name="last" placeholder="Surname">
                        Error message here!

                        Username
                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border" id="signup-uid" type="text" name="uid" placeholder="Username">
                        Error message here!

                        E-mail
                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border" id="signup-mail" type="email" name="mail" placeholder="E-mail">
                        Error message here!

                        Password
                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border" id="signup-pwd" type="text" name="pwd" placeholder="Password">
                        Hide
                        Error message here!

                        <input type="checkbox" id="accept-terms" class="cd-signin-modal__input ">
                        I agree to the Terms
                        Please accept the Terms!

<input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding"  name="signup-submit" id="signupbutton" type="submit" value="Create account" disabled>

                </form>

Lost your password? Please enter your email address. You will receive a link to create a new password.

                <form class="cd-signin-modal__form">

                        E-mail
                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border" id="reset-email" type="email" placeholder="E-mail">
                        Error message here!

                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding" type="submit" value="Reset password">

                </form>

Back to log-in

            Close

 Success!

You have successfully created an account and are now able to sign in to Learn Don't 4Get!

                <form class="cd-signin-modal__form">

                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding" type="button" id="back-to-login" value="Sign in">

                </form>

That shows the nav bar, and I have a JS function that displays a modal when the buttons are clicked.
The login verification form, located inside includes folder:
<?php

// Here we check whether the user got to this page by clicking the proper login button.
if (isset($_POST['login-submit'])) {

  // We include the connection script so we can use it later.
  // We don't have to close the MySQLi connection since it is done automatically, but it is a good habit to do so anyways since this will immediately return resources to PHP and MySQL, which can improve performance.
  require 'dbh.inc.php';

  // We grab all the data which we passed from the signup form so we can use it later.
  $mailuid = $_POST['mailuid'];
  $password = $_POST['pwd'];

  // Then we perform a bit of error handling to make sure we catch any errors made by the user. Here you can add ANY error checks you might think of! I'm just checking for a few common errors in this tutorial so feel free to add more. If we do run into an error we need to stop the rest of the script from running, and take the user back to the login form with an error message.

  // We check for any empty inputs. (PS: This is where most people get errors because of typos! Check that your code is identical to mine. Including missing parenthesis!)
  if (empty($mailuid) || empty($password)) {
    header("Location: ../new-index.php?loginerror=emptyfields&mailuid=".$mailuid);
    exit();
  }
  else {

    // If we got to this point, it means the user didn't make an error! :)

    // Next we need to get the password from the user in the database that has the same username as what the user typed in, and then we need to de-hash it and check if it matches the password the user typed into the login form.

    // We will connect to the database using prepared statements which work by us sending SQL to the database first, and then later we fill in the placeholders by sending the users data.
    $sql = "SELECT * FROM users WHERE uidUsers=? OR emailUsers=?;";
    // Here we initialize a new statement using the connection from the dbh.inc.php file.
    $stmt = mysqli_stmt_init($conn);
    // Then we prepare our SQL statement AND check if there are any errors with it.
    if (!mysqli_stmt_prepare($stmt, $sql)) {
      // If there is an error we send the user back to the signup page.
      header("Location: ../new-index.php?loginerror=sqlerror&mailuid=");
      exit();
    }
    else {

      // If there is no error then we continue the script!

      // Next we need to bind the type of parameters we expect to pass into the statement, and bind the data from the user.
      mysqli_stmt_bind_param($stmt, "ss", $mailuid, $mailuid);
      // Then we execute the prepared statement and send it to the database!
      mysqli_stmt_execute($stmt);
      // And we get the result from the statement.
      $result = mysqli_stmt_get_result($stmt);
      // Then we store the result into a variable.
      if ($row = mysqli_fetch_assoc($result)) {
        // Then we match the password from the database with the password the user submitted. The result is returned as a boolean.
        $pwdCheck = password_verify($password, $row['pwdUsers']);
        // If they don't match then we create an error message!
        if ($pwdCheck == false) {
          // If there is an error we send the user back to the signup page.
          header("Location: ../new-index.php?loginerror=wrongpwd&mailuid=".$mailuid);
          exit();
        }
        // Then if they DO match, then we know it is the correct user that is trying to log in!
        else if ($pwdCheck == true) {

          // Next we need to create session variables based on the users information from the database. If these session variables exist, then the website will know that the user is logged in.

          // Now that we have the database data, we need to store them in session variables which are a type of variables that we can use on all pages that has a session running in it.
          // This means we NEED to start a session HERE to be able to create the variables!
          session_start();
          // And NOW we create the session variables.
          $_SESSION['id'] = $row['idUsers'];
          $_SESSION['uid'] = $row['uidUsers'];
          $_SESSION['email'] = $row['emailUsers'];
          // Now the user is registered as logged in and we can now take them back to the front page! :)
          header("Location: ../new-index.php?login=success");
          exit();
        }
      }
      else {
        header("Location: ../new-index.php?loginerror=wronguidpwd&mailuid=");
        exit();
      }
    }
  }
  // Then we close the prepared statement and the database connection!
  mysqli_stmt_close($stmt);
  mysqli_close($conn);
}
else {
  // If the user tries to access this page an inproper way, we send them back to the signup page.
  header("Location: ../new-index.php");
  exit();
}

Essentially, instead of hearing to "new-index.php", I want it to do the exact same with the errors, but to the page in which it's called from.
Thanks! Sorry if this is blatantly obvious, I can't seem to get it to work!
.
.
.
.
.
.
EDIT: here are my files currently so you can see what's going on:
Database connection - dbh.inc.php

<?php
$dBServername = "localhost";
$dbuser = "root";
$userpw = "";
$database = "userdata";

// Create connection
$conn = mysqli_connect($dBServername, $dbuser, $userpw, $database);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$password = password_hash("test", PASSWORD_DEFAULT);
echo $password;

login.php
<?php
//login.php
require('dbh.inc.php');
$datetime = date("U");

 $obj = new stdClass();
     $obj->login = FALSE;  //initialized
     $obj->email = '';
     $obj->datetime = $datetime;
     $obj->dateread = date("D M j G:i:s T Y");

$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

  if(!($password=@$_POST["password"])){$obj->error = 'No password included.'; echo json_encode($obj); exit;}
  else {$password=$_POST["password"];}

  if(!($email=@$_POST["email"])){$obj->error = 'No email included.'; echo json_encode($obj); exit;}
  else {$email=$_POST["email"];}

      if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
          $obj->error = 'Invalid Email Address.';
          echo json_encode($obj);
          exit;
           }

 $db = new mysqli('localhost', $dbuser, $userpw, $database);   //These values kept in your conf.php file
 if (mysqli_connect_errno()) {
                             $obj->error = 'Error: Could not connect to database.';
                             error_log(json_encode($obj));
                             echo json_encode($obj);
                             exit;
                             }

 $query = "SELECT email, passwordHash              //A password hash created by password_hash()
           FROM users WHERE email = ?";
 $stmt = $db->prepare($query);
 $stmt->bind_param('s', $email);
 $stmt->execute();
 $stmt->store_result();
 $stmt->bind_result($emaildb, $passworddb);
 if (mysqli_connect_errno()) {$obj->error = 'Error: Could not connect to database.  ';
                             error_log(json_encode($obj));
                             echo json_encode($obj);
                             exit;
 }
 else{
     if($stmt->num_rows == 1) {
          while($stmt->fetch()){
             $obj->email = $emaildb;
             $obj->passwordHash = $passworddb;
          }

     } elseif($stmt->num_rows == 0) {
          $obj->error = 'No matching credentials found.';
          echo json_encode($obj);
          exit;
     }
}
$stmt->close();

if(password_verify($password , $obj->passwordHash)){
    $obj->login = 'success';
    echo json_encode($obj);
}

$db->close();
exit;
?>

login.html

        <input type="text" name="email" id="email" style="width:67%;" placeholder="Email*" />
        <input type="password" name="password" id="password" style="width:67%;" placeholder="Password*" />

    <button id="reviewButton" onclick="login()" class="buttonLogin">Log In</button>

A: As much as I'd love to be able to just do everything with PHP.  Javascript is really the other part of the equation that you need to be familiar with in order have that kind of control over the client side.  Specifically, Asynchronous Javascript allows the current page to interact with your PHP scripts all while staying on that page.  To do this, you will get rid of your  "form action=.... "  and, instead, use  "button onclick= aFunction().... " to execute a function that grabs the values from your inputs and posts them to your PHP and gets a result from that PHP file all while the browser sits in the same place.  The following is the gist of it:

<input type="text" name="email" id="email" style="width:67%;" placeholder="Email*"/>
<input type="password" name="password" id="password" style="width:67%;" placeholder="Password*"/>

<button id="reviewButton" onclick="login()" class="buttonLogin">Log In</button>

And your PHP file will look something like this:
<?php
//login.php
require('/path/to/conf.php');
$datetime = date("U");

 $obj = new stdClass();
     $obj->login = FALSE;  //initialized
     $obj->email = '';
     $obj->datetime = $datetime;
     $obj->dateread = date("D M j G:i:s T Y");

$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

  if(!($password=@$_POST["password"])){$obj->error = 'No password included.'; echo json_encode($obj); exit;}
  else {$password=$_POST["password"];}

  if(!($email=@$_POST["email"])){$obj->error = 'No email included.'; echo json_encode($obj); exit;}
  else {$email=$_POST["email"];}

      if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
          $obj->error = 'Invalid Email Address.';
          echo json_encode($obj);
          exit;
           }

 $db = new mysqli('localhost', $dbuser, $userpw, $database);   //These values kept in your conf.php file
 if (mysqli_connect_errno()) {
                             $obj->error = 'Error: Could not connect to database.';
                             error_log(json_encode($obj));
                             echo json_encode($obj);
                             exit;
                             }

 $query = "SELECT email, passwordHash
           FROM users WHERE email = ?";   //A password hash created by password_hash()
 $stmt = $db->prepare($query);
 $stmt->bind_param('s', $email);
 $stmt->execute();
 $stmt->store_result();
 $stmt->bind_result($emaildb, $passworddb);
 if (mysqli_connect_errno()) {$obj->error = 'Error: Could not connect to database.  ';
                             error_log(json_encode($obj));
                             echo json_encode($obj);
                             exit;
 }
 else{
     if($stmt->num_rows == 1) {
          while($stmt->fetch()){
             $obj->email = $emaildb;
             $obj->passwordHash = $passworddb;
          }

     } else($stmt->num_rows == 0) {
          $obj->error = 'No matching credentials found.';
          echo json_encode($obj);
          exit;
     }
}
$stmt->close();

if(password_verify($password , $obj->passwordHash)){
    $obj->login = 'success';
    echo json_encode($obj);
}

$db->close();
exit;
?>

To be clear, you conf.php file could be as simple as this:
/path/to/conf.php
<?php
//conf.php

//For Database
$dbuser='username';
$userpw='strongPassword';
$database='nameofDatabase';

?>


text:
Q: Using SOAP Savon gem and Rails I am trying to establish a connection using the SOAP gem, called Savon. I can't make sense from the documentation on the website, I have this URL: "https://www.example.com/loginWeb/rvu.aspx", and this credentials username: "user", password: "pass".
My code is this (rails console):
client = Savon::Client.new("https://www.example.com/loginWeb/rvu.aspx")
client.wsse.credentials 'user', 'pass'

I get this: (event trying with "digest")
HTTPI executes HTTP GET using the net_http adapter
OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

I downloaded SoapUI and I get this error when I try to connect to the URL:
Error loading [http://www.example.com/loginWeb/rvu.aspx?WSDL]: org.apache.xmlbeans.XmlException: org.apache.xmlbeans.XmlException: error: Unexpected character encountered (lex state 3): '&

So what is going on ? Any help?

A: I suppose it's the same issue as here: you're trying to access a site with self-signed SSL certificate.
One way to fix it is to prevent Savon checking it:
client = Savon::Client.new("https://www.example.com/loginWeb/rvu.aspx")
client.http.auth.ssl.verify_mode = :none
client.wsse.credentials 'user', 'pass'


text:
Q: jQuery call to functions I have the following code:
var x;
x=$(document);
x.ready(initEvents);

function initEvents()
{
    var x;
    x = $("#send");
    x.click(pressButton);
    x = $("#clean");
    x.click(cleanForm);
}

/*this method  validates the form*/
function pressButton()
{
    $("#form1 :input").attr("disabled", true);

    $("#form1").validate(
    {   rules:
        {
            //sets the rules for validate
        },
        messages:
        {
            //sets the message for validates
        },
        submitHandler: function (form)
        {
            //send the form
        }
    });
}

My problem is that if a put this line $("#form1 :input").attr("disabled", true); the validates don't executes but if I commented the validate function works great. The question is why can't I execute the two lines? What am I doing wrong in the code?

A: I don't think this is your actual problem here, but it's worth noting that you should pay attention to getting your curly braces right when you're working with JavaScript. Adding the line break between the key name and the opening brace of the value may cause the key name to be interpreted as a JavaScript label in some cases.
It would be better to generally use this style, to avoid running into strange errors later on:
// Why complicate this?
$(document).ready(initEvents);

function initEvents() {
  $("#send").click(pressButton);
  $("#clean").click(cleanForm);
}

/*this method  validates the form*/
function pressButton() {
  $("#form1 :input").attr("disabled", true);

  $("#form1").validate({
    rules: {
      // the rules for validate
    },
    messages: {
      //sets the message for validates
    },
    submitHandler: function (form) {
      //send the form
    }
  });
}

A: I solved my problem like this, disabled the form after the validation putting the line in the submithanlder of the validation
/*this method  validates the form*/
function pressButton()
{

$("#form1").validate(
{   rules:
    {
        //sets the rules for validate
    },
    messages:
    {
        //sets the message for validates
    },
    submitHandler: function (form)
    {
        //disable the form
        $("#form1 :input").attr("disabled", true);
        //send the form
    }
});
}


text:
Q: How to dynamically set the width of a div according to the screensize? I have a web application where I would like to dynamically change the width of a div according to the screen size, just like this application does: https://gyazo.com/ce99185a58e5c7d8cef9f8375952db8c
Ideally I would love to know how I could achieve this on my own. Any information would be greatly appreciated. This is how I tried to do it, but it does not work:
The application is divided into two equal segments, left and right.
I am using vue-styled-components to set css properties with javascript.
import styled from "vue-styled-components";

let widthProps = { dynamicWidth: String }

const RightContent = styled('div', widthProps)`
    display: block;
    height: 100vh;
    width: ${props => props.dynamicWidth};
    max-height: 100vh;
    padding-top: 32px;
    padding-right: 48px;
    padding-bottom: 16px;
    padding-left: 48px;
`;

export default RightContent;

I thought I could dynamically set the divs width with something like this:
<RightContent id="rightContent" :dynamicWidth="dynamicWidth">

onResize() {
  window.addEventListener("resize", () => {
    let rightcontent = window.document.getElementById("rightContent");
    if (rightcontent) {
      //the 96 is padding left and padding right
      let width = rightcontent.offsetWidth - 96;
      console.log(width);
      this.valueIWantToSetTheWidthOfTheDivTo = width;
      // this.dynamicWidth = `${width}px`;
    }
  });
}

I would call this function in the created() hook.
However, once I uncomment this line: // this.dynamicWidth = `${width}px`;, the width gets set and is static, so it will always be the value it was when the screen got resized the first time.
I created a codesandbox with my problem.


text:
Q: Browsers not responding to Rails3 force_ssl (Rails 3, https) My client wants her entire app (all links) to run over HTTPS/SSL.
I put
config.force_ssl = true

in config/application.rb. However, now Safari and Firefox and Opera are all griping about app, with different errors.
(From Firefox, "ssl_error_rx_record_too_long")
Do I need a certificate? Or is there a simpler solution?

A: It turned out that I needed to do the following to make the entire Rails 3.2 app run over SSL:
1) In config/application.rb, instead of 'config.force_ssl', use the gem 'rack-ssl-enforcer', and
config.middleware.use Rack::SslEnforcer

2) Create a certificate using openssl/mod-ssl (CentOS)
3) Use "thin" instead of WEBrick - thin seems easier to configure for SSL.
Thin gets configured to use the certificate files generated in Step 2.


text:
Q: Design Pattern Factory Method question - why the factory method in ConcreteCreator won't be available yet? I am reading "Design Patterns" by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides. In chapter of factory method, there's one paragraph:

"Factory method in C++ are always virtual functions and are often pure
virtual. Just be careful not to call factory methods in the Creator's
constructor - the factory method in the ConcreteCreator won't be
available yet."

I don't understand why the factory method in ConcreteCreator won't be available yet? is it because C++ is a compiled language therefore the method of the children class won't be available as the parent class is compiled first? Thank you.


text:
Q: Pitch changing similar to Talking Tom I am using the Dirac library for changing the pitch of recorded sound similar to Talking Tom application. Everything works perfect when I included this library. But I am facing one issue, actually that's not an issue, processing delay. After I record the input audio as .caf file, the same file is processing to convert to .aif which contains the audio of recorded sound with pitch changed. For this process, it's taking some time. So when I record a sound and try to autoplayback, I am getting a delay for playbacking the recorded sound due to this processing of conversion. My requirement is a clone of Talking Tom application, in which the playback is happening immediately after the recording. Am I doing any wrong? If anyone can help me to solve this issue, really helpful. Do I need to send the portion of code I am using.
Thanks in advance


text:
Q: Change UIView frame Height and width from user input from UIText field I am able to change height and width of UIView frame on button click by hardcoding the height and width, but i am unable change it when i get input from user in  UItext field in CGFloat format.
`
 import UIKit

  class SetBorderSizeViewController: UIViewController{

@IBOutlet weak var WidthText: UITextField!
@IBOutlet weak var Height: UITextField!
@IBOutlet weak var View_border: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    View_border.isHidden = true
}

   //Change UIView Height and width frame  on  "ChangeSizeButton" Button Press.....

@IBAction func ChangeSizeButton(_ sender: Any) {
     View_border.isHidden = false
    View_border.layer.borderWidth = 5
 /// Here i want to get user input from text field...
    View_border.frame.size.height = 20
    View_border.frame.size.width = 80
   }

   }

`
Anyone here who can update my code according to my requirements please???.

A: Try this:
@IBAction func ChangeSizeButton(_ sender: Any) {
         View_border.isHidden = false
        View_border.layer.borderWidth = 5
     /// Here i want to get user input from text field...
        View_border.frame.size.height = CGFloat(Float(WidthText.text!)!)
        View_border.frame.size.width = CGFloat(Float(Height.text!)!)
        self.View_border.layoutIfNeeded()
       }

A: This code works as well:
class ViewController: UIViewController {

    // MARK: IBOutlets

    @IBOutlet private weak var resizableView: UIView!
    @IBOutlet private weak var widthTextField: UITextField!
    @IBOutlet private weak var heightTextField: UITextField!

    // MARK: IBActions

    @IBAction private func didResizeButtonTapped(_ sender: UIButton) {
        let (newWidth, newHeight) = convertValues()
        resizableView.frame.size.width = newWidth
        resizableView.frame.size.height = newHeight
    }

}

// MARK: Private Methods

private extension ViewController {

    func convertValues() -> (width: CGFloat, height: CGFloat) {
        let width = Float(widthTextField.text ?? "0")
        let height = Float(heightTextField.text ?? "0")
        return (CGFloat(width ?? 0.0), CGFloat(height ?? 0.0))
    }

}

but in my case I am using constraints for my "resizableView" so my view invalidated each time. In this case you can create reference for width and height constraints and set them new values like:
widthConstraint.constant = <your_value>


text:
Q: Post-processing the output result from Dymola when there are only 2 elements in the result I am trying to use the MATLAB scripts shipped with Dymola to post-process the output result of Dymola. But in some cases, the output data in the .mat file only have 2 elements, how could I get the data between 10s and 100s in this kind of cases?
It's a parameter or variable that is not time depending so it's stored in a compact way. I understand the mechanism, but it is not user-friendly when post-processing the data in MATLAB, I have to find the "wrong" dimensional data. How could I fix this issue?

A: I recommend creating some simple logic that looks at the size of the variable and then automatically puts it into some dictionary, list, etc. From there you can manipulate the variable. I know you are asking for Matlab but here is a Python solution that I have used which may help you get started:
    varNames_param_base=[]
    varNames_var_base=[]
    for i, val in enumerate(r.varNames()):
        if np.size(r.values(val)) == 4:
            varNames_param_base.append(val)
        else:
            varNames_var_base.append(val)

I used those lines in this file.
In the example r.varNames() is a list of all the variable names (i.e., strings) which are read from the resulting Dymola .mat file. r.values gets the value of the variable name currently being used in the for loop (i.e., val).

A: You may also consider converting your result file to SDF (a simple HDF5 representation), because that format does not use any clever storage options (if I remember correctly).


text:
Q: Primefaces dataExporter to xls Float number becomes text in spreadsheet cell Environment:

*

*jsf 2.2

*primefaces 6.1

*wilfly 10

I'm trying to export a dataTable to an excel with dataExporter from primefaces, but I'm firstly getting
<p:commandButton id="btnExpExcel"
                 alt="#{msgs.inv_exportinvoices}"
                 ajax="false">
    <p:dataExporter type="xls" target="lstFactures"
                    fileName="invoices"/>
</p:commandButton>
<p:dataTable id="lstFactures" var="inv"
...

Option 1 I get in xls pex. 83.2 but we use , as decimal instead of .
...
<p:column headerText="#{msgs.total}">
    <h:outputText value="#{inv.total}">
        <f:convertNumber locale="#{localeBean.locale}"/>
    </h:outputText>
</p:column>
...

Option 2 I get in xls pex. 83,2 but excel deal with that as text instead of number
...
<p:column headerText="#{msgs.total}">
    <h:outputText value="#{inv.total}" />
</p:column>
...

**Option3 ** with

public void postProcessXLS(Object document) {
        HSSFWorkbook wb = (HSSFWorkbook) document;
        HSSFSheet sheet = wb.getSheetAt(0);
        HSSFRow header;
    HSSFCellStyle cellStyle = wb.createCellStyle();
    cellStyle.setFillForegroundColor(HSSFColor.GREEN.index);
    cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    int ind = 0;
    for (int row = 0; row < invoices.size() + 1; row++) {
        header = sheet.getRow(row);
        for (int col = 0; col < header.getPhysicalNumberOfCells(); col++) {
            ...
                }
                if (col == 5) {
                    HSSFCell cell = header.getCell(col);
                    //Total is a float
                    cell.setCellValue(invoices.get(ind).getTotal());
                    ind++;
                }
            }
        }
    }
}

I also tried to exportFuction="#{inv.total}" but I got some kind of error exportFunction="#{inv.total}": Method not found...
What I'm getting in xls is the following

A: All the fields in p:dataTable are exported as text.
If you want to convert a value in a different format, you have to implement a postProcessor method.
Example:
page.xhtml
<p:dataExporter type="xls" target="lstFactures" fileName="invoices" postProcessor="#{bean.ppMethod}" />

Class Bean
public void ppMethod(Object document) {
    Workbook workbook = (Workbook) document;
    ...
    CellStyle totalCellStyle = workbook.createCellStyle();

    totalCellStyle.setDataFormat(workbook.createDataFormat().getFormat("#,##0.00"));

    Cell currentCell = workbook.getSheetAt(0).getRow(0).getCell(0);

    currentCell.setCellValue(Double.parseDouble(currentCell.getStringCellValue()));
    currentCell.setCellStyle(defaultCellStyle);
    ...
}


text:
Q: YouTube V3 API -- Filtering related video information by duration, doesn't seem to work I am trying to filter out 'long' videos from the response of a YouTube V3 API request.
I have:
var relatedVideoInformationRequest = gapi.client.youtube.search.list({
    part: 'snippet',
    relatedToVideoId: 'oqrxjeDIWPs',
    maxResults: 10,
    //  If the relatedToVideoId parameter has been supplied, type must be video.
    type: 'video',
    videoDuration: 'medium'
});

relatedVideoInformationRequest.execute(function (relatedVideoInformationResponse) {
    console.log(relatedVideoInformationResponse);
});

The first result is longer than 20 minutes and the videoDuration parameter does not seem to have been applied. This happens in my code along with the YouTube API playground.
Am I doing something wrong or is this a bug?

A: You are right, I filed a bug internally. Feel free to file a bug in public issue tracker to track.


text:
Q: Javascript Breakout game. Changing ball speed at score interval I am looking for a little help on adding on to some code for a Breakout game using Javascript within Tumult Hype. I am looking to make it so that once you hit a certain score the ball speed will increase.
Here is the code so far without the speed booster.
var input1 = event.which || event.keyCode;

if ((input1 == "37") && (window.setLoopLeft == false)) { // LEFT ARROW PRESSED
    window.setLoopLeft = true;
    window.intervalLeft = setInterval(moveLeft, 5);
} else if ((input1 == "39") && (window.setLoopRight == false)) { // RIGHT ARROW PRESSED
    window.setLoopRight = true;
    window.intervalRight = setInterval(moveRight, 5);
} else if ((input1 == "32") && (window.ballLaunched == false)) { // SPACE BAR PRESSED
    window.ballLaunched = true;
    // RUN THE MOVEBALL FUNCTION EVERY 10 MILLISECONDS
    window.intervalMoveBall = setInterval(moveBall, window.ballSpeed);
}

function moveBall() {
    var ballLeft = parseInt(hypeDocument.getElementById("ball").style.left);
    var ballTop = parseInt(hypeDocument.getElementById("ball").style.top);

This is the code I am adding onto. Now what I was planning was to do what create a global variable to apply to the window.intervalMoveBall. I would then write a new function that would detect the score value at 1000 points and double the balls speed making it move every 5 miliseconds instead of 10.
Now what I am not sure how to do is actually write the if statement so that it detects the score value.  I was wondering if anybody might be able to show me how to right that or even be able to tell me if using a global and a new function with an if statement will even work for this or not.

A: You are currently using setInterval, so to change the time interval you would have to clear the original interval, and start a new one with the new time interval.  A simpler approach is to make the moveBall function responsible for calling itself with a setTimeout (and the same for the moveLeft and moveRight), like this...
var input1 = event.which || event.keyCode;

if ((input1 == "37") && (window.setLoopLeft == false)) { // LEFT ARROW PRESSED
    window.setLoopLeft = true;
    window.intervalLeft = setInterval(moveLeft, 5);
} else if ((input1 == "39") && (window.setLoopRight == false)) { // RIGHT ARROW PRESSED
    window.setLoopRight = true;
    window.intervalRight = setInterval(moveRight, 5);
} else if ((input1 == "32") && (window.ballLaunched == false)) { // SPACE BAR PRESSED
    window.ballLaunched = true;
    moveBall();
}

function moveBall() {
    setTimeout(moveBall, window.ballSpeed);
    // the rest of your moveBall function
}

This means that we can set a different timespan every time moveBall runs, with some conditional logic, for example,
function moveBall() {
    setTimeout(moveBall, window.score > 1000 : 5 ? 10);
    // the rest of your moveBall function
}

Obviously this is an infinite loop, so you would also want to add some way of stopping this, such as a check that the game hasn't finished, for example,
function moveBall() {
    if (window.gameFinished) {
        return;
    }

    setTimeout(moveBall, window.score > 1000 : 5 ? 10);
    // the rest of your moveBall function
}

Just as an aside, it can get quite unmaintainable to use lots of global variables stored on the window object, so it might be worth looking into JavaScript namespacing.


text:
Q: Can you pass parent function keyword arguments to a child function easily? By this, I mean that often I have a function with a keyword argument, such as debug=False, and I want to pass this to a child function with the same keyword argument, which would result in something like debug=debug.
Here is an example:
def makeDirNearbyBuildings(lat, lon, lat1=None, lon1=None, area=1000, debug=False, debugimg=False):

  if lat1 == None:
    buildings = getNearbyBuildings(lat, lon, area=area, debug=debug)

This works, but isn't very readable.
Is there a programatically nicer way to do this in Python?


text:
Q: Is division by zero considered error or failure? When my program stops working due to division by 0 then is it considered error or failure?
Error is called when a human action produces an incorrect result. Failure is when we get different result than expected. I'm just wondering if the unexpected stop from program is a error by human or failure of the program?

A: It is considere as an error. Or we can also called this an exception. And if u dont want to  prevent this u can use exception handling.
Depending on the programming environment and the type of number (e.g. floating point, integer) being divided by zero, it may generate positive or negative infinity, generate an exception, generate an error message, cause the program to terminate.

A: It is a type of failure when it is in compile time but it is an error because usually this type of an error occur when the program is compiled and then executed


text:
Q: Faithful Operations in algebra I am trying to find a minimum $m$ such that the group $D_4$ has a faithful operation on the set of order $m$.
I think we need to find an injective map from $D_4 \rightarrow Perm(X)$. But I am not sure how to do/find m?
Any solutions?

A: Consider the action of $D_4$ on a set of four points, which we may view as the vertices of a square. Is this action faithful?
If so, bearing in mind $|D_4|=8$, what can we say about any homomorphism $\phi:D_4\to S_m$ for $m<4$?


text:
Q: InvalidStateError on websocket object I'm just starting learning websockets, andI get a strange error:
<script type="text/javascript">
    window.onload = function(){
        var service = new WebSocket("ws://localhost:8080/websocket/test");
        service.onmessage = function(event){
            alert("message");
        }
        service.onopen = function(){
            service.send("hello!");
        }
        service.onclose = function(){
            alert("closed");
        }
        service.onerror = function(){
            alert("error");
        }

        service.send("test");
        service.close();
    }

</script>

on the line:
            service.send("test");

I get:
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

Am I missing something important?

A:
The WebSocket.onopen property is an EventHandler that is called when the WebSocket connection's readyState changes to OPEN; this indicates that the connection is ready to send and receive data.

Once you've opened your connection, you can begin transmitting data to the server.

window.onload = function() {
  var service = new WebSocket("wss://echo.websocket.org");
  service.onmessage = function(event) {
    alert("onmessage event: "+event.data);
  }
  service.onopen = function() {
    service.send("test"); //Will work here!
    //^^^^^^^^^^^^^^^^^
    service.send("hello!");
  }
  service.onclose = function() {
    alert("closed");
  }
  service.onerror = function() {
    alert("error");
  }

  //Can't close while a connection is still being established.
  //service.close();
}

A: If you use Websocket().send() outside your service.onopen(), you can still check the readyStatebefore sending message, like this:
    websocket.sendmessage = async function(msg) {
       while (this.readyState === 0) {
            await sleep(200);
       }
       this.send(msg);
    };


text:
Q: An authorized user can view other authorized page because of setAuthCookie I'm working on an asp.net application. it consist of two modules:

*

*End Users

*Managers
I've built both modules and integrated it into one. Now comes the question, I verify the end user from a database and issue permissions to the user to view members-only resources by
setAuthCookie()

When the user presses the logout button it will automatically logout by
signout()

while I was going through with stuff, I came to know that an end user also views manager side of application because he is authorized to view and I authorized him by 'sethAuthCookie'.
(when user request login page i.e for manager and for end user, it will redirect to some action page which I also do in page_load event by 'httpcontext.current.request.isauthorized').
The above is also valid in case of a manager.
Is there any way that an end user can view only his side of application? vice versa
Possible solutions came to my mind:

*

*Create a cookie which stores an encrypted form user type i.e he is manager or end user and check it in page_load event.

*store it in some session variable
These both are insecure and very hard coded.
Is there any way to resolve this problem using some built-in or rich approach ?
Thanks in advance!