text:
Q: How to load json in main method Flutter? I'm trying to load a json file into my main() app method.
Can you tell me if this is possible? I've tryed File and rootBundle but it seems that Assets' folder are not ready yet.
here is my code:
ASSETS
  assets:
    - assets/settings/settings.json

MAIN METHOD
void main() async {
    final file = await rootBundle.loadString('assets/settings/settings.json');
      final data = jsonDecode(file);
      Settings settings = Get.put(Settings.fromJson(data), permanent: true);
  runApp(MyApp());
}

A: Found the Solution using FutureBuilder
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  _load() async {
    final file = await rootBundle.loadString('assets/j.json');
    final data = await jsonDecode(file);
    print(data.toString());
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: _load(),
        builder: (_, AsyncSnapshot<dynamic> snapshot) {
          return !snapshot.hasData
              ? Container(
                  color: Colors.white,
                  child: Center(
                      child: Container(
                    child: CircularProgressIndicator(),
                    width: 20,
                    height: 20,
                  )),
                )
              : MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        appBarTheme: AppBarTheme(
          titleTextStyle: Theme.of(context).textTheme.headline1,
        ),
      ),
      home: Scaffold(
        body: Text("Body"),

        // MaxWidthButton(),
      ),
    );
        });
  }
}

A: I dont seems it is, instead try on MyApp and make it statefullWidget

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    _load();
  }

  _load() async {
    final file = await rootBundle.loadString('assets/j.json');
    final data = await jsonDecode(file);
    print(data.toString());
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        appBarTheme: AppBarTheme(
          titleTextStyle: Theme.of(context).textTheme.headline1,
        ),
      ),
      home: Scaffold(
        body: Text("Body"),

        // MaxWidthButton(),
      ),
    );
  }
}


text:
Q: Delta Lake OSS table large volume due to versioning I have set up a Spark standalone cluster and use Spark Structured Streaming to write data from Kafka to multiple Delta Lake tables - simply stored in the file system. So there are multiple writes per second.
After running the pipeline for a while, I noticed that the tables require a large amount of storage on Disk. Some tables require 10x storage compared to the sources.
I investigated the Delta Lake table versioning. When I DESCRIBE a selected table, it's stated that the sizeInBytes is actually around 10 GB, although the corresponding folder on the disk takes over 100 GB.
DESCRIBE DETAIL delta.`/mnt/delta/bronze/algod_indexer_public_txn_flat`

So I set the following properties:
ALTER TABLE delta.`/mnt/delta/bronze/algod_indexer_public_txn_flat`
SET TBLPROPERTIES ('delta.logRetentionDuration'='interval 24 hours', 'delta.deletedFileRetentionDuration'='interval 1 hours')

and then performed a VACUUM:
VACUUM delta.`/mnt/delta/bronze/algod_indexer_public_txn_flat`

But still, after several days, the size on the disk stays at around 100GB. Altough constantly performing a VACUUM.
How can I overcome this issue?

*

*Spark 3.2.1

*Delta Lake 1.2.0

Thanks in advance!
UPDATE:
Looks like when I manually delete the json logs in _delta_log the VACUUM actually cleans old versions, so I assume some of the properties are not applied?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to load a listbox of states depending on the selected country in RemixRun? I love Remix, but there are some things I wonder how it could be achieved.
Let say I have 2 listboxes, one for the country and a second for the state.
How would I achieve the loading of the states depending on the country selection from the previous list?

A: Here's a quick demo. I'm using useFetcher to load data when country changes. As you can see I also sent the initial data from the loader.
export const loader: LoaderFunction = async ({ request }) => {
  const url = new URL(request.url)
  const country = url.searchParams.get('country') || 'United States'
  const countries = Object.keys(statesByCountry)
  const states = statesByCountry[country]

  return json({ countries, country, states })
}

export default function Index() {
  const initialData = useLoaderData()
  const fetcher = useFetcher()
  const { countries, country, states } = fetcher.data ?? initialData

  const handleChange = (e) => {
    const params = new URLSearchParams()
    params.set('country', e.target.value)
    fetcher.load(`?index&${params.toString()}`)
  }
  return (

Remix Dual Lists!

        <select
          name="country"
          defaultValue={country}
          onChange={handleChange}
          size={10}
        >
          {countries.map((country) => (
            <option>{country}</option>
          ))}
        </select>
        <select name="state" size={10}>
          {states.map((state) => (
            <option>{state}</option>
          ))}
        </select>

  )
}

https://codesandbox.io/s/remix-dual-lists-epcxvu?file=/app/routes/index.tsx


text:
Q: Is it possible to continue a Flash game session on a different computer? I am currently playing a flash-game (Mardek RPG chapter 3) and I found it pretty long. I've done quite a lot of progress on a computer that's not mine (it belongs to my relatives), and now I want to continue playing this session on my computer.
I'm playing it off-line, so the saved data is on the computer.
Is it possible to transfer the saved data to my own computer? If so, how can it be done?

A: Assuming your relative's computer is running windows, flash local storage is usually found in a location such as:
C:/Users/[USERNAME]/AppData/Roaming/Macromedia/Flash Player/SharedObjects/[RANDOM LETTERS]/[NAME OF WEBSITE]
I'd suggest checking there for any files, I can't remember if Roaming is a hidden folder by default, so you might need to show hidden folders. Copy the related files and place them on your computer. This should let you continue your game.

A: The solution depends on your operating system.  From the Kongregate forums:

*

*Go to Folder Settings in Windows and turn hidden folders ON.

*Next, go to
C:\Users\YOUR WINDOWS
  USERNAME\AppData\Roaming\Macromedia\FlashPlayer\#SharedObjects\SOME
  RANDOM LETTERS AND NUMBERS\

*There should be two folders, one named chat.kongregate.com and one named armorgames.com or a different website you played it on

*Copy the save files/folders from the source computer to the destination computer

*You're DONE! You can now pick up where you left off, and hopefully make progress towards the new badges (which WILL appear… eventually)

The folder locations for various OS's are as follows:
On Microsoft Windows NT 5.x and 6.x, they are stored in:
 %APPDATA%\Macromedia\Flash Player\#SharedObjects\
 %APPDATA%\Macromedia\Flash Player\macromedia.com\support\flashplayer\sys\

On Mac OS X, they are stored in:
~/Library/Preferences/Macromedia/Flash Player/#SharedObjects/
~/Library/Preferences/Macromedia/Flash Player/macromedia.com/support/flashplayer/sys/

On Linux or Unix, they are stored in:
~/.macromedia/Flash_Player/#SharedObjects/
~/.macromedia/Flash_Player/macromedia.com/support/flashplayer/sys/

For Linux and Unix systems, if the open-source Gnash plugin is being used instead of the official Adobe Flash, they will instead be found at:
~/.gnash/SharedObjects/

http://en.wikipedia.org/wiki/Local_shared_object#File_locations


text:
Q: Google -Bigquery Error " Not found: Dataset prime-poc:churn was not found in location US" While predicting the Customer churn for Kaggle dataset using Google's Big query.  I am hitting "Not found: Dataset prime-poc:churn was not found in location US".
This is depie the fact that churn_table is loaded in US location. Please let me know how to overcome this issue. My verification efforts are stalled due to this issue. Any quick help will  be greatly appreciate.
Big query command used :
FROM
      ccpchurndataset.Churn_table
NOTE :  both ccpchurndataset and Churn_table are in US location only.

A: Specify fully qualified name ProjectId.DatasetId.TableId enclosed in () tick sign.


text:
Q: Best approach to mutate(add/remove bindings) a Guice injector while maintaining state I am hoping to redefine or update some bindings within a Module which is in turn used by an Injector. I realise that Modules are immutable and once a binding is sucked and injected its definition cannot change for all practical purposes.
I would like to add/change/remove bindings while keeping singletons already living in an Injector. Changing is a simple case as one can achieve this effecct by using a Provider. However dynamically adding or removing a Key (binding definition) is a bit more tricky.
Any thoughts if this should or can be practically done.
I am thinking the best way is to recreate an injector each time an add/remove binding occurs copying definitions from the original to the new one, Any existing singletons would be redefined by toInstance rather than to implementation type etc.

A: Child injectors can be used to accomplish this, but it requires some setup. Child injectors will prevent long-lived bindings from depending on short-lived ones. Here's an example:
class ForeverModule extends AbstractModule {
  ...
}

class TemporaryModule extends AbstractModule {
  ...
}

class Main {
    public static void main(String... args) {
        Injector foreverInjector = Guice.createInjector(new ForeverModule());

        Injector injector = foreverInjector.createChildInjector(
                new TemporaryModule());
        /*
         * Do stuff with the injector as you would normally. When you
         * get bored of that injector, create a replacement injector
         * as a child of the long-lived injector.
         */
    }
}

Singleton bindings in the forever module will last as long as that module exists. Singleton bindings in the temporary module will last as long as you're using the corresponding injector.
Warning: By default, just-in-time bindings will be created in the top-level injector. If you need a binding to be short-lived, you need to bind both the interface and the implementation in your child injector's module. That looks like this:
public void configure() {
    bind(Foo.class).to(RealFoo.class);
    bind(RealFoo.class);
}


text:
Q: ASP.NET Repeater Control Checkbox issue Overview: Clicking on text of first CheckBox in a repeater control clicks the last one. I know why this is happening; association of label tag with element id chkMarkedForDeletion and when that label is clicked it selects the last CheckBox, as all the CheckBoxes have same ID.. damn you repeater control!! I am wondering if there is any way to avoid this? Easy way would be to create individual labels and associate correctly to each CheckBox but that defeats the supposed default behaviour of a CheckBox.
Repeater code:
<asp:Repeater ID="childNodesDataRepeater" runat="server">
    <ItemTemplate>

                    <asp:CheckBox ID="chkMarkedForDeletion" runat="server" EnableViewState="true" Text="Remove"
                        Checked='<%# DataBinder.Eval(Container.DataItem, "IsMarkedForDeletion") %>' />

                    <asp:CheckBox ID="chkHighImpactCause" runat="server" EnableViewState="true" Text="High Impact Cause"
                        Checked='<%# DataBinder.Eval(Container.DataItem, "IsHighPriority") %>' />

                    <asp:Label ID="header002" runat="server" Text="What caused this problem?" />

                    <asp:TextBox ID="txtProblemCausedBy" runat="server" EnableViewState="true" Width="100%"
                        Text='<%# DataBinder.Eval(Container.DataItem, "Description") %>' />

                    <asp:HiddenField ID="nodeIdentifier" runat="server" EnableViewState="true" Value='<%# DataBinder.Eval(Container.DataItem, "AnalysisID") %>' />

    </ItemTemplate>
</asp:Repeater>

Generated HTML Code for CheckBox:
<INPUT id=chkMarkedForDeletion type=checkbox name=TabContainer$tabProblemResolution$frmProblemResolution1$childNodesDataRepeater$ctl00$chkMarkedForDeletion>
Remove
...
...
<INPUT id=chkMarkedForDeletion type=checkbox name=TabContainer$tabProblemResolution$frmProblemResolution1$childNodesDataRepeater$ctl02$chkMarkedForDeletion>
Remove

Issue:

Thanks,
Abhi

A: Make sure the ClientIDMode on the repeater is not set to "Static".
This setting is inheritable from the parent, which goes all the way up to web.config. So if you have to set the ClientIDMode explicitly on the repeater, it means that some parent overrides the default (Predictable) to "Static".


text:
Q: what is the meaning of this statement (chaIntVal >= 0x10 ? chaIntVal : chaIntVal | 0x60) Hi Please somebody can explain me the meaning of this conditional statement? This is a java code.
(chaIntVal >= 0x10 ? chaIntVal  : chaIntVal | 0x60)

A: It means:
int res;
if(chaIntVal >= 0x10) {
    res = chaIntVal;
} else {
    res = chaIntVal | 0x60;   // binary or
}

A: It is a ternary operator which means this.
condition ? value_if_true : value_if_false;

It is almost equivalent to
if(condition){
    // when true do this
}else{
    // when false do this
}

A: This expression returns chaIntVal as is if chaIntVal > 16; otherwise it will set bits 5 and 6 to 1 of chaIntVal (binary OR http://www.xcprod.com/titan/XCSB-DOC/binary_or.html) and returns it.

A: If the high bits after the 4 low bits of the value are not set (value in range 0-15), do set bits x11x xxxx.


text:
Q: sometimes I don't want to be forced to interact with the topmost window. How can I get around it, without closing it? We've all seen this when we opened a setting or preference window from a context menu in a program we're using-- the window flashes/flickers and forces you to close it if you want to get at information 'below' it in the z-order window stack.
What is this 'feature' called?
Is there a way to prevent Windows from forcing interaction?


text:
Q: how to fetch a data based on id conditions were same here is my below xml under that table due based on CTD_CTD_PKG_ID(some time under table CTD_CTD_PKG_ID id was same means we need take data from both tables ) this pack id we need to generate a text file with the help of xsl style sheet but how to write logic code in xslt
for some fields data were same for that type of records for me dont want to repeat once again only once i need but how to control if i am getting two records of CTD_LANG_ID needed to display once but i have written xslt i was thinking it was not correct we will fail when we are have xml with one more table with different package id(CTD_CTD_PKG_ID) at that time lang id may be different than E but this xslt were showing E it self ...
 <?xml version="1.0" standalone="yes"?>
 <NewDataSet>

<RECORD_TYPE_CODE>CTD</RECORD_TYPE_CODE>
<MSG_TYPE_CODE>O102</MSG_TYPE_CODE>
<CTD_SEQ_NUM>089938</CTD_SEQ_NUM>
<CTD_CTD_PKG_ID>345</CTD_CTD_PKG_ID>
<CTD_LANG_ID>E</CTD_LANG_ID>

<RECORD_TYPE_CODE>ITD</RECORD_TYPE_CODE>
<MSG_TYPE_CODE>O103</MSG_TYPE_CODE>
<CTD_SEQ_NUM>089939</CTD_SEQ_NUM>
<CTD_CTD_PKG_ID>345</CTD_CTD_PKG_ID>
<CTD_LANG_ID>E</CTD_LANG_ID>

</NewDataSet>

I HAVE A WRITTEN MY OWN XSLT LOGIC BUT IT DOESN'T WORK
<?xml version="1.0" encoding="utf-8"?>

<xsl:output method="text" indent="no" omit-xml-declaration="yes" />

<xsl:param name="PackageId"  />

<xsl:template match="/">
    <xsl:apply-templates select="NewDataSet/Table[CTD_CTD_PKG_ID ='345']"/>
</xsl:template>

<xsl:template match="NewDataSet/Table[CTD_CTD_PKG_ID ='345']">

    <xsl:value-of select= "concat(':25:',./TRAN_TYPE_CODE)"/>,<xsl:text/>
    <xsl:if test ="./RECORD_TYPE_CODE"  >
        <xsl:if test=" position() > 1"></xsl:if>
        <xsl:text/><xsl:value-of select= "concat(':20:',./RECORD_TYPE_CODE)"/>,<xsl:text/>
    </xsl:if>
    <xsl:if test ="./MSG_TYPE_CODE" >
        <xsl:if test=" position() > 1"></xsl:if>
        <xsl:text/><xsl:value-of select= "concat(':21:',./MSG_TYPE_CODE)"/>,<xsl:text/>
    </xsl:if>
    <xsl:if test ="./CTD_SEQ_NUM" >
        <xsl:if test=" position() > 1"></xsl:if>
        <xsl:text/><xsl:value-of select= "concat(':22:',./CTD_SEQ_NUM)"/>,<xsl:text/>
    </xsl:if>
</xsl:template>

Execpected output
:25:E,:20:CTD,:21:O102N,:22:089938,:20:ITD,:21:O103N,:22:089939,

A: Here is a sample stylesheet:
<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

  <xsl:output method="text"/>

  <xsl:param name="packageId" select="345"/>

  <xsl:template match="/">
    <xsl:apply-templates select="NewDataSet/Table[CTD_CTD_PKG_ID = $packageId]"/>
  </xsl:template>

  <xsl:template match="Table">
    <xsl:if test="position() > 1">,</xsl:if>
    <xsl:apply-templates select="RECORD_TYPE_CODE | MSG_TYPE_CODE | CTD_SEQ_NUM"/>
  </xsl:template>

  <xsl:template match="Table/*">
    <xsl:if test="position() > 1">,</xsl:if>
    <xsl:value-of select="."/>
  </xsl:template>

</xsl:stylesheet>

A: To stay with your code...
You are performing xsl:if tests starting from the wrong context. The template context is Table. Also the xsl:text is used in the wrong way. For instance, you should change test with:
<xsl:if test="RECORD_TYPE_CODE">
    <xsl:value-of select= "RECORD_TYPE_CODE"/><xsl:text>,</xsl:text>
</xsl:if>

This if you want omit empty values in your output like ,,. Moreover you will need to change the final condition to avoid the last comma:
<xsl:if test="CTD_SEQ_NUM">
        <xsl:value-of select= "CTD_SEQ_NUM"/>
            <xsl:if test="count(following-sibling::Table)>0">
                <xsl:text>,</xsl:text>
            </xsl:if>
</xsl:if>


text:
Q: Тире перед большими буквами PHP регулярные выражения Как из masterAtHome получить master-at-home ?

A: Это типовая задача преобразования Camel Case строк в аналог Snake Case (с минусами вместо подчеркиваний).
Вот один из самых простых вариантов преобразования:
echo strtolower(preg_replace("/(?!^)([A-Z])/", '-$1', 'masterAtHome'));

В примере выше, группа символов (?!^) используется для игнорирования заглавной буквы, если она идет первой в строке.
Рабочий пример на Ideone.

A: Можно поступить следующим образом
<?php
  echo preg_replace_callback(
    '/(?<!^)([A-Z])/',
    function($match) { return '-'.strtolower($match[1]); },
    'masterAtHome');


text:
Q: books in which post-human has become a discorporate distributed artifact 20 or maybe 30 years ago I read two books by a pair of authors which I would like to identify. They didn't strike me as remarkable at the time but in retrospect they were very imaginative even if they weren't memorable. It's a long time ago so I'm going to be unfortunately vague and I may even be conflating more than book.
The first book involved a hierarchy of space-travellers and they are somehow involved in a vortex visiting Earth. Mankind enters the vortex in spaceships but they interact with beings at the bottom of the hierarchy. Near the end of the book there is mention of a separate inverted spiral but I can't remember anything more than that.
I can be more specific about the other book because it had a visit by humans to a post-human who had become a nebulous solar-system sized intelligence. I remember that they asked a question of this being and he replied but warned that he had only partially arrived at the communication point so he may change his answer when more of him was assembled.
A snippet comes to mind in which someone says of a post-human that he had become distributed as an asteroidal ring but I think that this is a different book.
There is a good example of a distributed intelligence in "House of Suns" by Alastair Reynolds but this isn't the book (and neither is "The Black Cloud by Fred Hoyle).


text:
Q: Не сохраняется перевод строки в textarea Хэллоу,
в textarea вводится какой-то текст. Рядом кнопка с js-функцией, при нажатии на которую текст обрабатывается и возвращается в textarea. Проблема в том, что текст возвращается без переводов строк. Как сохранить переводы строк?
Например, такая функция. Все работает, но результат возвращается одной сплошной строкой.

function addcomma(comma) {
    var str = document.getElementById('comma').value.replace('\r', '');
    var result = str.split('\n');
    var i = 0;
    while (i < result.length) {
        document.getElementById('comma').value = result[i] + ',';
        i++;
    }
}

A: document.getElementById('comma').value = result.join(',\n'); не катит?
A: var str = document.getElementById('comma').value.replace('\r', '');
var result = str.split('\n');

и тут невидно в чем проблема? Сначала косишь в строке все r а потом хочешь их split как-то нелогично.


text:
Q: How do I log all current locals/parameters with log4net? is there a way to log all local variables and values (inc. params) when logging using log4net?
I know I can just add each value to the log message, but was wondering if there was a simpler way.
I also understand that this could affect performance, however, it wouldn't be used that much.
[how about without log4net?  is there another method to capture all locals?]

A: log4net does not provide a way to log all parameter values and locals. You can print them all yourself with calls like
Log.DebugFormat("{0}: {1}", /* get parameter name */, /* get parameter value */)

I was thinking StackFrame could get you that information, but it can only tell you about parameter types and method return types. There is no way to get locals.
You would have to use an interception framework like Castle DynamicProxy. The IInvocation parameter of the Intercept method provides the arguments
Log.DebugFormat("{0}.{1}({2})", invocation.TargetType.Name, invocation.Method.Name, string.Join(", ", invocation.Arguments));

A: I've used the interceptor tecnique to log all WCF call.
You need to add some parameters to your appender (controller, action, user, datain, dataout)
Hope this help
public interface IOpenUserName
    {
        string UserName { get; set; }
    }

    [AttributeUsage(AttributeTargets.Method)]
    public class LogWcfAttribute : Attribute
    {

    }

    public class LogWcfInterceptor : IInterceptor
    {
        private readonly ILogger _logger;

        public LogWcfInterceptor(ILogger logger)
        {
            _logger = logger;
        }

        public void Intercept(IInvocation invocation)
        {
            if (WcfHelper.HasLogWcfAttribute(invocation.MethodInvocationTarget))
            {
                Exception exception = null;

                var openUser = (IOpenUserName) invocation.InvocationTarget;

                log4net.LogicalThreadContext.Properties["controller"] = invocation.InvocationTarget.GetType().Name;
                log4net.LogicalThreadContext.Properties["action"] = invocation.MethodInvocationTarget.Name;

                log4net.LogicalThreadContext.Properties["user"] = openUser != null ? openUser.UserName : string.Empty;
                log4net.LogicalThreadContext.Properties["datain"] = SerializeObject(invocation.Arguments);

                try
                {
                    invocation.Proceed();
                }
                catch (Exception ex)
                {
                    exception = ex;
                }
                finally
                {
                    log4net.LogicalThreadContext.Properties["dataout"] = SerializeObject(invocation.ReturnValue);
                    _logger.Debug("OPENOTA", exception);
                }

                if (exception != null) throw exception;
            }
            else
            {
                invocation.Proceed();
            }
        }

        public static string SerializeObject(object toSerialize)
        {
            if (toSerialize == null) return string.Empty;

            var xmlSerializer = new XmlSerializer(toSerialize.GetType());
            var textWriter = new StringWriter();

            xmlSerializer.Serialize(textWriter, toSerialize);
            return textWriter.ToString();
        }
    }

    public static class WcfHelper
    {
        public static bool HasLogWcfAttribute(MethodInfo methodInfo)
        {
            return methodInfo.IsDefined(typeof(LogWcfAttribute), false);
        }
    }


text:
Q: How to get the FFT of a numpy array to work? I'm reading a specific column of a csv file as a numpy array. When I try to do the fft of this array I get an array of NaNs. How do I get the fft to work? Here's what I have so far:
#!/usr/bin/env python
from __future__ import division

import numpy as np
from numpy import fft

import matplotlib.pyplot as plt

fileName = '/Users/Name/Documents/file.csv'

#read csv file
df = np.genfromtxt(fileName, dtype = float, delimiter = ',', names = True)

X = df['X'] #get X from file

rate = 1000. #rate of data collection in points per second
Hx = abs(fft.fft(X))
freqX = fft.fftfreq(len(Hx), 1/rate)

plt.plot(freqX,Hx) #plot freqX vs Hx

A: Presumably there are some missing values in your csv file.  By default, np.genfromtxt will replace the missing values with NaN.
If there are any NaNs or Infs in an array, the fft will be all NaNs or Infs.
For example:
import numpy as np

x = [0.1, 0.2, np.nan, 0.4, 0.5]
print np.fft.fft(x)

And we'll get:
array([ nan +0.j,  nan+nanj,  nan+nanj,  nan+nanj,  nan+nanj])

However, because an FFT operates on a regularly-spaced series of values, removing the non-finite values from an array is a bit more complex than just dropping them.
pandas has several specialized operations to do this, if you're open to using it (e.g. fillna).  However, it's not too difficult to do with "pure" numpy.
First, I'm going to assume that you're working with a continuous series of data because you're taking the FFT of the values.  In that case, we'd want to interpolate the NaN values based on the values around them. Linear interpolation (np.interp) may not be ideal in all situations, but it's not a bad default choice:
For example:
import numpy as np

x = np.array([0.1, 0.2, np.nan, 0.4, 0.5])
xi = np.arange(len(x))

mask = np.isfinite(x)
xfiltered = np.interp(xi, xi[mask], x[mask])

And we'll get:
In [18]: xfiltered
Out[18]: array([ 0.1,  0.2,  0.3,  0.4,  0.5])

We can then calculate the FFT normally:
In [19]: np.fft.fft(xfiltered)
Out[19]:
array([ 1.50+0.j        , -0.25+0.34409548j, -0.25+0.08122992j,
       -0.25-0.08122992j, -0.25-0.34409548j])

...and get a valid result.

A: If your data contains NaN values, you need to interpolate them. Alternatively, you can calculate the spectrum using the Fourier equation where np.sum is replaced with np.nansum. With this approach you don't need to interpolate NaN values, although the amount of missing data will effect the spectrum. More missing data will result in a noisy spectrum and hence inaccurate spectral values.
Below is a MWE to illustrate the concept, with a graph showing the result. The MWE illustrates how to calculate the single-sided amplitude spectrum of a simple reference signal containing a number of missing values.
#!/usr/bin/python
# Python code to plot amplitude spectrum of signal containing NaN values
# Python version 2.7.13

from __future__ import division
import numpy as np
import pylab as pl
import random

LW = 2 #line width
AC = 0.5 #alpha channel
pi = np.pi

def periodogramSS(inputsignal,fsamp):
 N = len(inputsignal)
 N_notnan = np.count_nonzero(~np.isnan(inputsignal))
 hr = fsamp/N #frequency resolution
 t = np.arange(0,N*Ts,Ts)
 #flow,fhih = -fsamp/2,(fsamp/2)+hr #Double-sided spectrum
 flow,fhih = 0,fsamp/2+hr #Single-sided spectrum
 #flow,fhih = hr,fsamp/2
 frange = np.arange(flow,fhih,hr)
 fN = len(frange)
 Aspec = np.zeros(fN)
 n = 0
 for f in frange:
  Aspec[n] = np.abs(np.nansum(inputsignal*np.exp(-2j*pi*f*t)))/N_notnan
  n+=1
 Aspec *= 2 #single-sided spectrum
 Aspec[0] /= 2 #DC component restored (i.e. halved)
 return (frange,Aspec)

#construct reference signal:
f1 = 10 #Hz
T = 1/f1
fs = 10*f1
Ts = 1/fs
t = np.arange(0,20*T,Ts)
DC = 3.0
x = DC + 1.5*np.cos(2*pi*f1*t)

#randomly delete values from signal x:
ndel = 10 #number of samples to replace with NaN
random.seed(0)
L = len(x)
randidx = random.sample(range(0,L),ndel)
for idx in randidx:
 x[idx] = np.nan

(fax,Aspectrum) = periodogramSS(x,fs)

fig1 = pl.figure(1,figsize=(6*3.13,4*3.13)) #full screen
pl.ion()

pl.subplot(211)
pl.plot(t, x, 'b.-', lw=LW, ms=2, label='ref', alpha=AC)

#mark NaN values:
for (t_,x_) in zip(t,x):
 if np.isnan(x_):
  pl.axvline(x=t_,color='g',alpha=AC,ls='-',lw=2)

pl.grid()
pl.xlabel('Time [s]')
pl.ylabel('Reference signal')

pl.subplot(212)
pl.stem(fax, Aspectrum, basefmt=' ', markerfmt='r.', linefmt='r-')
pl.grid()
pl.xlabel('Frequency [Hz]')
pl.ylabel('Amplitude spectrum')

fig1name = './signal.png'
print 'Saving Fig. 1 to:', fig1name
fig1.savefig(fig1name)

The reference signal (real) is shown in blue with missing values marked with green. The single-sided amplitude spectrum is shown in red. The DC component and amplitude value at 10 Hz are clearly visible. The other values are caused by the reference signal being broken up by the missing data.


text:
Q: How do I iterate over a stream in Java using for? I have this code:
List<String> strings = Arrays.asList("a", "b", "cc");
for (String s : strings) {
    if (s.length() == 2)
        System.out.println(s);
}

I want to write it using a filter and a lambda:
for (String s : strings.stream().filter(s->s.length() == 2)) {
    System.out.println(s);
}

I get Can only iterate over an array or an instance of java.lang.Iterable.
I try:
for (String s : strings.stream().filter(s->s.length() == 2).iterator()) {
    System.out.println(s);
}

And I get the same error. Is this even possible? I would really prefer not to do stream.forEach() and pass a consumer.
Edit:  it's important to me not to copy the elements.

A: You need an iterable to be able to use a for-each loop, for example a collection or an array:
for (String s : strings.stream().filter(s->s.length() == 2).toArray(String[]::new)) {

Alternatively, you could completely get rid of the for loop:
strings.stream().filter(s->s.length() == 2).forEach(System.out::println);

You mention you don't want to refactor your for loop but you could extract its body in another method:
strings.stream().filter(s->s.length() == 2).forEach(this::process);

private void process(String s) {
  //body of the for loop
}


text:
Q: How to pass a DATE_SUB() as a parameter in update query in nodejs I am updating a field with another field which is datetime(datatype), So while updating it should be a minute less So i am using DATE_SUB(). But i am getting  error SyntaxError: missing ) after argument list near INTERVAL
code:
for(var k=0;k<grouppedArray[i][j].length;k++){
    if(grouppedArray[i][j][k+1]){
        db.query('update userRegister set  logout= ? where userId = ? and catId = ?', [SUBDATE(grouppedArray[i][j][k+1].login, INTERVAL 1 MINUTE), 1, grouppedArray[i][j][k].userId, grouppedArray[i][j][k].catId], function (err, updatedLogout) {

        }
    }
}

Where am i going wrong here? Please help

A: Try the following :
for(var k=0;k<grouppedArray[i][j].length;k++){
    if(grouppedArray[i][j][k+1]){
        db.query('update userRegister set  logout= SUBDATE(?, INTERVAL 1 MINUTE) where userId = ? and catId = ?', [grouppedArray[i][j][k+1].login, grouppedArray[i][j][k].userId, grouppedArray[i][j][k].catId], function (err, updatedLogout) {

        }
    }
}

or
for(var k=0;k<grouppedArray[i][j].length;k++){
    if(grouppedArray[i][j][k+1]){
        db.query('update userRegister set  logout= ? - INTERVAL 1 MINUTE where userId = ? and catId = ?', [grouppedArray[i][j][k+1].login, grouppedArray[i][j][k].userId, grouppedArray[i][j][k].catId], function (err, updatedLogout) {

        }
    }
}


text:
Q: Is it possible to make a crytographically strong/safe salt with PHP's built in functions and no mcrypt? I need to generate a salt (to pass to crypt) but the server doesn't have mcrypt (and I do not have the ability to put it there). Is there a way I can do it with openssl_random_pseudo_bytes or another built-in PHP function?
It is important that it has safe-randomness.
My mcrypt was:
$salt = "$" . $algorithm . "$" . $length . "$";
$salt .= substr( str_replace( "+", ".", base64_encode( mcrypt_create_iv( 128, MCRYPT_DEV_URANDOM ) ) ), 0, 22 );
return $salt;

How would I do this without mcrypt?


text:
Q: What are some examples of where using parentheses in a program lowers readability? I always thought that parentheses improved readability, but in my textbook there is a statement that the use of parentheses dramatically reduces the readability of a program.  Does anyone have any examples?

A: I can find plenty of counterexamples where the lack of parentheses lowered the readability, but the only example I can think of for what the author may have meant is something like this:
if(((a == null) || (!(a.isSomething()))) && ((b == null) || (!(b.isSomething()))))
{
   // do some stuff
}

In the above case, the ( ) around the method calls is unnecessary, and this kind of code may benefit from factoring out of terms into variables.  With all of those close parens in the middle of the condition, it's hard to see exactly what is grouped with what.
boolean aIsNotSomething = (a == null) || !a.isSomething();  // parens for readability
boolean bIsNotSomething = (b == null) || !b.isSomething();  // ditto
if(aIsNotSomething && bIsNotSomething)
{
   // do some stuff
}

I think the above is more readable, but that's a personal opinion.  That may be what the author was talking about.
Some good uses of parens:

*

*to distinguish between order of operation when behavior changes without the parens

*to distinguish between order of operation when behavior is unaffected, but someone who doesn't know the binding rules well enough is going to read your code.  The good citizen rule.

*to indicate that an expression within the parens should be evaluated before used in a larger expression: System.out.println("The answer is " + (a + b));
Possibly confusing use of parens:

*

*in places where it can't possibly have another meaning, like in front of a.isSomething() above.  In Java, if a is an Object, !a by itself is an error, so clearly !a.isSomething() must negate the return value of the method call.

*to link together a large number of conditions or expressions that would be clearer if broken up.  As in the code example up above, breaking up the large paranthetical statement into smaller chunks can allow for the code to be stepped through in a debugger more straightforwardly, and if the conditions/values are needed later in the code, you don't end up repeating expressions and doing the work twice.  This is subjective, though, and obviously meaningless if you only use the expressions in 1 place and your debugger shows you intermediate evaluated expressions anyway.

A: Apparently, your textbook is written by someone who hate Lisp.
Any way, it's a matter of taste, there is no single truth for everyone.

A: I think that parentheses is not a best way to improve readability of your code. You can use new line to underline for example conditions in if statement. I don't use parentheses if it is not required.

A: Well, consider something like this:
Result = (x * y + p * q - 1) % t and
Result = (((x * y) + (p * q)) - 1) % t
Personally I prefer the former (but that's just me), because the latter makes me think the parantheses are there to change the actual order of operations, when in fact they aren't doing that. Your textbook might also refer to when you can split your calculations in multiple variables. For example, you'll probably have something like this when solving a quadratic ax^2+bx+c=0:
x1 = (-b + sqrt(b*b - 4*a*c)) / (2*a)
Which does look kind of ugly. This looks better in my opinion:
SqrtDelta = sqrt(b*b - 4*a*c);
x1 = (-b + SqrtDelta) / (2*a);

And this is just one simple example, when you work with algorithms that involve a lot of computations, things can get really ugly, so splitting the computations up into multiple parts will help readability more than parantheses will.

A: Parentheses reduce readability when they are obviously redundant.  The reader expects them to be there for a reason, but there is no reason.  Hence, a cognitive hiccough.
What do I mean by "obviously" redundant?

*

*Parentheses are redundant when they can be removed without changing the meaning of the program.

*Parentheses that are used to disambiguate infix operators are not "obviously redundant", even when they are redundant, except perhaps in the very special case of multiplication and addition operators.  Reason: many languages have between 10–15 levels of precedence, many people work in multiple languages, and nobody can be expected to remember all the rules.  It is often better to disambiguate, even if parentheses are redundant.

*All other redundant parentheses are obviously redundant.
Redundant parentheses are often found in code written by someone who is learning a new language; perhaps uncertainty about the new syntax leads to defensive parenthesizing.
Expunge them!

You asked for examples.  Here are three examples I see repeatedly in ML code and Haskell code written by beginners:

*

*Parentheses between if (...) then are always redundant and distracting.  They make the author look like a C programmer.  Just write if ... then.

*Parentheses around a variable are silly, as in print(x).  Parentheses are never necessary around a variable; the function application should be written print x.

*Parentheses around a function application are redundant if that application is an operand in an infix expression.  For example,
(length xs) + 1

should always be written
length xs + 1

A: Anything taken to an extreme and/or overused can make code unreadable.  It wouldn't be to hard to make the same claim with comments.  If you have ever looked at code that had a comment for virtually every line of code would tell you that it was difficult to read.  Or you could have whitespace around every line of code which would make each line easy to read but normally most people want similar related lines (that don't warrant a breakout method) to be grouped together.

A: You have to go way over the top with them to really damage readability, but as a matter of personal taste, I have always found;
return (x + 1);

and similar in C and C++ code to be very irritating.

A: If a method doesn't take parameters why require an empty () to call method()? I believe in groovy you don't need to do this.


text:
Q: Grab only required characters from http api I collect data from http api and one of the api is to check balance of my remaining credits. Here is what I want to do, fetch file_contents and insert that remaining credits from the received output.
        $bal =  file_get_contents("http://www.example.com/balancecheck.php?username=123&api_password=123");

this outputs data like this
username = 123
validity = 31/03/2103
remaining credits = 5000
user credits = 3000

Now, I want to grab only 5000 (which is remaining credits and insert the same to my db)
I wanted to use explode but no luck. Please could someone help

A: From the PHP docs:

Description
int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
  Searches subject for a match to the regular expression given in pattern.

So, what you need is:
preg_match( "/remaining credits = (\d+)/", file_get_contents($url), $matches);
$balance = $matches[1];

Edit:
I had an extra $ before the file_get_contents function call. I thought PHP made you put dollar signs everywhere. It should be fixed now.
Edit 2:
I had $balance = $matches[0] before, but it has been corrected. The parentheses (\d+) captures just the number as a match and adds that to the end of the $matches array.


text:
Q: C# program querying an Access database in a network folder takes longer than querying a local copy I have a C# application that uses an MS Access database (.mdb file). I share my database with network users so they can access the database with my application.
When I run my application it takes longer to execute the query on the network database, while that same query takes less time on my local machine.
Can any one provide advice on how to reduce this performance issue with an Access database on a network share?

A: Of course queries accessing a database over the network are not going to be as fast as the same queries accessing a database on the local hard drive. Unfortunately it is fairly common for a developer to build an application that runs okay locally, but slows significantly once it has been deployed on the network. (This can be true for any developer, not just ones using Access databases.)
In my experience, the three most important things to do regarding the performance of an application using a shared Access database are:
Index Appropriately
Table scans are murder on a shared-file database like Access. Be sure to have indexes on fields that are used in WHERE clauses or are used to JOIN tables.
To illustrate, I ran the following command on a 122 MB .accdb file containing one table with 421,184 rows:
cmd.CommandText =
    "SELECT COUNT(*) AS n FROM zz_sys_archive " +
    "WHERE archived Between #2013-01-01# And #2013-04-01#";

With no index on the [archived] field the command took 78 seconds to execute and generated 107 MB of network traffic.
After adding an index to the [archived] field that same command took 0.4 seconds to execute and generated 0.9 MB of network traffic.
(However, don't go nuts and index everything because extraneous indexes will just slow down INSERT and UPDATE operations.)
Query Intelligently
Even with appropriate indexes in place a poorly-designed query will result in table scans and slow your application down. For example, the query
cmd.CommandText =
    "SELECT COUNT(*) AS n FROM zz_sys_archive " +
    "WHERE Year(archived) = 2013";

is not sargable, meaning that it cannot use the index on the [archived] field and does a table scan with the same results as before (~80 seconds to complete). However, the equivalent query
cmd.CommandText =
    "SELECT COUNT(*) AS n FROM zz_sys_archive " +
    "WHERE archived >= #2013-01-01# AND archived < #2014-01-01#";

took about one second to execute.
Don't Read What You Don't Need
With a local database it is often tempting to just read the whole table and ignore what you don't really want. Accessing a database over the network makes that much more expensive, so think about what you really need before you just "SELECT * FROM wherever".


text:
Q: Out-of-proc COM factory CreateInstance returns E_UNEXPECTED I am trying to create instance of COM object using factory.
My server code is:
int main(int, char* argv[])
{
    HRESULT result = CoInitializeEx(NULL, COINIT_MULTITHREADED);

    Factory factory;
    DWORD regID = 0;
    result = CoRegisterClassObject(CLSID_InterractionInterfaceFactory, (IClassFactory*) &factory, CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE, &regID);

    MSG ms;
    while(GetMessage(&ms, 0, 0, 0))
    {
        TranslateMessage(&ms);
        DispatchMessage(&ms);
    }

    CoRevokeClassObject(regID);

    CoUninitialize();

    return 0;
}

My client code is:
int main(int, char*[])
{
    HRESULT result;
    result = CoInitialize(NULL);

    IClassFactory* factory = NULL;

    result = CoGetClassObject(CLSID_InterractionInterfaceFactory, CLSCTX_LOCAL_SERVER, NULL, IID_IClassFactory, (void**)&factory);

    if (S_OK == result)
    {
        IInterractionInterface* iface = NULL;
        result = factory->CreateInstance(NULL, IID_InterractionInterface, (void**)&iface);
        **// HERE IT RETURNS E_UNEXPECTED**
    }

    CoUninitialize();

    return 0;
}

My QueryInterface method:
STDMETHODIMP InterractionInterface::QueryInterface(REFIID riid, LPVOID FAR * ppv)
{
    *ppv = NULL;

    if (riid == IID_IUnknown)
    {
        *ppv = (IUnknown*)this;
    }
    if (riid == IID_InterractionInterface)
    {
        *ppv = (IInterractionInterface*)this;
    }
    else
    {
        *ppv = NULL;
        return E_NOINTERFACE;
    }

    reinterpret_cast<IUnknown*>(*ppv)->AddRef() ;
    return S_OK;
}

I can not get what i am doing wrong. It enters to QueryInterface, the object is valid, reference counter is incremented, i am returning from Factory::CreateInstance(..., LPVOID* obj) S_OK, and obj is filled successfully, but client gets empty object and return code E_UNEXPECTED.
What i am doing wrong?
My interace is:
DEFINE_GUID(CLSID_InterractionInterfaceFactory, 0x84d55f4a, 0xff3c, 0x43b2, 0xa1, 0xa3, 0x3a, 0xd3, 0xe9, 0x96, 0xc4, 0x26);

DEFINE_GUID(IID_InterractionInterface, 0xc191f3ac, 0x79e1, 0x4be3, 0xbb, 0x87, 0xac, 0x7a, 0xb8, 0x24, 0xd6, 0xb9);

class IInterractionInterface : public IUnknown
{
public:
    STDMETHOD (Test(int)) PURE;
};


text:
Q: Как лучше реализовать тест на JavaScript для проверки знания английскому языку

let test = document.querySelector('#test');

let questions = [

    {
        text: 'Я программист',
        right: 'I',
        variant: 'AM',
        variant2: 'PROGRAMMER'
    },

];

for (let question of questions) {
    let div = document.createElement('div');
    test.appendChild(div);

    let otvet = document.createElement('div');
    test.appendChild(otvet);
    otvet.classList.add('otvet');
    div.classList.add('otvet');

    let otvets = document.createElement('div');
    test.appendChild(otvets);
    otvets.classList.add('otvet');
    div.classList.add('otvet');

    let div1 = document.createElement('div');
    div1.textContent = question.right;
    otvet.appendChild(div1);
    div1.classList.add('otvet');

    let div2 = document.createElement('div');
    div2.textContent = question.variant;
    otvet.appendChild(div2);
    div2.classList.add('otvet');

    let div3 = document.createElement('div');
    div3.textContent = question.variant2;
    otvet.appendChild(div3);
    div3.classList.add('otvet');
    let p = document.createElement('p');
    p.innerHTML = question.text;
    div.appendChild(p);

    function insert(elem, word) {

        let start = elem.selectionStart;
        elem.value = elem.value.substring(0, start) + word +
            elem.value.substring(elem.selectionEnd, elem.value.length)
        elem.focus();
        elem.setSelectionRange(start, start + word.length)
    }

    let input = document.createElement('input');
    input.dataset.right = question.right;
    let input2 = document.createElement('input');
    input2.dataset.variant2 = question.variant2;

    let input3 = document.createElement('input');
    input3.dataset.variant = question.variant;

    div1.addEventListener('click', function() {
        insert(input, div1.textContent = question.right)
        otvet.removeChild(div1);
        otvets.appendChild(input);
    });
    div2.addEventListener('click', function() {
        insert(input2, div2.textContent = question.variant)
        otvet.removeChild(div2);
        otvets.appendChild(input2);
    });
    div3.addEventListener('click', function() {
        insert(input3, div3.textContent = question.variant2)
        otvet.removeChild(div3);
        otvets.appendChild(input3);
    });
}

let button = document.querySelector('#button');

button.addEventListener('click', function() {
    let inputs = document.querySelectorAll('#test input');

    for (let input of inputs) {
        input.classList.remove('correct');
        input.classList.remove('incorrect');

        if (input.value == input.dataset.right

        ) {
            input.classList.add('correct');

        } else if (input.value == input.dataset.variant) {
            input.classList.add('correct');
        } else {
            input.classList.add('incorrect');
        }

    }

})
#test div {
    margin-bottom: 20px;
  margin-left: 30px;
  margin-top: 20px;
}

#button {
    margin-left: 30px;
}

input {
    display: block;
    width: 50%;
    height: calc(1.5em + .75rem + 2px);
    padding: .375rem .75rem;
    font-size: 1rem;
    font-weight: 400;
    line-height: 1.5;
    color: #495057;
    background-color: #fff;
    background-clip: padding-box;
    border: 2px solid #ced4da;
    border-radius: .25rem;
    transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
.input2{
    display: block;
    width: 50%;
    height: calc(1.5em + .75rem + 2px);
    padding: .375rem .75rem;
    font-size: 1rem;
    font-weight: 400;
    line-height: 1.5;
    color: #495057;
    background-color: #fff;
    background-clip: padding-box;
    border: 2px solid #ced4da;
    border-radius: .25rem;
    transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
#button {
    display: inline-block;
    font-weight: 400;
    text-align: center;
    vertical-align: middle;
    user-select: none;
    color: #fff;
    background-color: #007bff;
    border-color: #007bff;
    padding: .375rem .75rem;
    font-size: 1rem;
    line-height: 1.5;
    border-radius: .25rem;
    transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
.otvet{
   display:flex;
   flex-direction: row;
   border: 2px solid;
}
.correct {
    border: 2px solid green;
}
.incorrect {
    border: 2px solid red;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="./style.css">

    <title>Россия</title>

<button id="button">Проверить</button>

Всем доброго вечера. Я начал делать маленькое приложение для изучения английского языка.
Если кратко это должно работать так:
Пользователю предлагается составить несколько английских предложений,
предложения выбираются в рандомном порядке.
Для начала я хотел бы сделать проверку на правильность порядка слов в предложение. Подскажите, пожалуйста, как сделать проверку на правильность результатов по коду.
Буду рад любой помощи.

A: Сам отвечаю на свой вопрос. Я все таки реализовал, то что хотел. Код я представляю в простом варианте.
Что я сделал
Я сделал мини-тест  на проверку знаний английского языка. Представлено выражение на русском языке Я программист . Ниже блок с кнопками, нажимая на них-выставляем слова в нужном порядке слова. Далее нажимая на кнопку 'проверка'- происходит проверка на правильность выражения, если слово не правильно- оно подсвечивается красной рамкой.

const questionsRus = ["Я", "программист"]
const questions = ["I'm", "a", "programmer"];
const answers = [];

const text1 = document.querySelector('.vopros-text1');
const text2 = document.querySelector('.vopros-text2');
const text3 = document.querySelector('.vopros-text3');
const text4 = document.querySelector('.otvet-text');
const text5 = document.querySelector('.otvet-text5');
const text6 = document.querySelector('.otvet-text6');
const buttonProverka = document.querySelector('.button__proverka');
const otvet = document.querySelector('.otvet-variant');

const buttonText1 = document.querySelector('.text4');
const buttonText2 = document.querySelector('.text5');
const buttonText3 = document.querySelector('.text6');

//текст кнопок
const textVariant1 = buttonText1.textContent = "programmer";
const textVariant2 = buttonText2.textContent = "a";
const textVariant3 = buttonText3.textContent = "I'm";

const pushed1 = () => {
    let res = answers.push(textVariant1);
    text4.textContent = textVariant1;
    otvet.appendChild(text4);
    return res;
}

const pushed2 = () => {
    let res = answers.push(textVariant2);
    text5.textContent = textVariant2;
    otvet.appendChild(text5);
    return res;
}

const pushed3 = () => {
    let res = answers.push(textVariant3);
    text6.textContent = textVariant3;
    otvet.appendChild(text6);
    return res;
}

buttonText1.addEventListener("click", pushed1);
buttonText2.addEventListener("click", pushed2);
buttonText3.addEventListener("click", pushed3);

text1.textContent = questionsRus[0];
text2.textContent = questionsRus[1];
text3.textContent = questionsRus[2];

const checkAnswers = (a, b) => {
    return a.map((item, idx) => item === b[idx]);
}
buttonProverka.addEventListener("click", proverka);

function proverka() {
    let res = checkAnswers(answers, questions);

    if (res[0] === false) {
        text4.classList.add('border-red');
    } else {
        text4.classList.add('border-green')
    };

    if (res[1] === false) {
        text5.classList.add('border-red');
    } else {
        text5.classList.add('border-green')
    };
    if (res[2] === false) {
        text6.classList.add('border-red')
    } else {
        text6.classList.add('border-green')
    };

   }
.vopros{
    display:flex;
    margin:10px;
    }
    .otvet{
        display:flex;
    }
    .border-red{
        border:solid 1px red;
    }
    .border-green{
        border:solid 1px green;
    }

    .otvet-variant{
        display:flex;
    }
    .otvet-text{
        margin-right: 10px;
    }
    .otvet-text5{
        margin-right: 10px;
    }
    .otvet-text6{
        margin-right: 10px;
    }
    .vopros-text1{
        margin-right: 10px;
    }
    .vopros-text2{
        margin-right: 10px;
    }
<!DOCTYPE html>

<meta charset="utf-8">
<link rel="stylesheet" href="index.css" type="text/css"/>

    <button class="text4"></button>
    <button class="text5"></button>
    <button class="text6"></button>

<button class="button__proverka">Проверить</button>


text:
Q: awk delete column in a "sparse" text file I've a text file with 4 columns like this one
2010-01-03 10:58:00     268435456
2010-01-03 10:59:00     268435456
2010-01-03 11:00:00 -134    0
2010-01-03 11:01:00 -131    0
...

In column 3 you can find the values I want to keep, in column 4 you can find an error code.
Both columns, however, does not have values in every line. Thus awk '!($4="")' file deletes the 4th column only when the 3rd column exists. Otherwise the error code is written into column 3 and thus mixed up with my observation values.
How can I really discard column 4?

A: "Fields are normally separated by whitespace sequences (spaces, TABs, and newlines), not by single spaces. Two spaces in a row do not delimit an empty field. The default value of the field separator FS is a string containing a single space, " ". If awk interpreted this value in the usual way, each space character would separate fields, so two spaces in a row would make an empty field between them. The reason this does not happen is that a single space as the value of FS is a special case—it is taken to specify the default manner of delimiting fields." from "GAWK: Effective AWK Programming"
Solution, In your case the fields is separated by tabs or spaces
awk -F "[\t ]" '{$4=""}1' file

or
awk -F "[[:blank:]]" '{$4=""}1' file

you get,

2010-01-03 10:58:00
2010-01-03 10:59:00
2010-01-03 11:00:00 -134
2010-01-03 11:01:00 -131

A: Just skip last column.
awk '{$NF=""}1' file

output
2010-01-03 10:58:00
2010-01-03 10:59:00
2010-01-03 11:00:00 -134
2010-01-03 11:01:00 -131


text:
Q: Excel Data Entry made faster with Macro? I am currently trying write a macro in excel to help shorten the time that this will take.  I have water sample data for 10 different manholes and each were sampled quarterly since 1994. Because of this, I have a total of 75 dates that I need to input per manhole for this spreadsheet. Each of these dates has 97 rows of information that is input into this sheet and then a space before going to the next date.  My ultimate question is, how can I take the dates shown from the first image and copy the first one 97 times, then second 97 times without redundantly doing so.  Example is the image attached.

A: In column A have an integer sequence, starting at 0 and going up. In column B, do integer division on column A (QUOTIENT). You'll integer divide by the number of times you want things repeated (97). Then in column C, use VLOOKUP, taking the value from column B as the index into your lookup table, to "copy" the values for dates.
If you have the same measurements for each date, you can use a new column that uses MOD on column A, then use that as the index for a second VLOOKUP into your measurements lookup table.


text:
Q: Kubernetes vs. Docker: What Does It Really Mean? I know that Docker and Kubernetes aren't direct competitors. Docker is the container platform and containers are coordinated and scheduled by Kubernetes, which is a tool.
What does it really mean and how can I deploy my app on Docker for Azure ?

A: Short answer:

*

*Docker (and containers in general) solve the problem of packaging an application and its dependencies. This makes it easy to ship and run everywhere.

*Kubernetes is one layer of abstraction above containers. It is a distributed system that controls/manages containers.
My advice: because the landscape is huge... start learning and putting the pieces of the puzzle together by following a course. Below I have added some information from the:

*

*Introduction to Kubernetes, free online course from The Linux Foundation.

Why do we need Kubernetes (and other orchestrators) above containers?

In the quality assurance (QA) environments, we can get away with running containers on a single host to develop and test applications. However, when we go to production, we do not have the same liberty, as we need to ensure that our applications:

*

*Are fault-tolerant

*Can scale, and do this on-demand

*Use resources optimally

*Can discover other applications automatically, and communicate with each other

*Are accessible from the external world

*Can update/rollback without any downtime.

  Container orchestrators are the tools which group hosts together to form a cluster, and help us fulfill the requirements mentioned above.

Nowadays, there are many container orchestrators available, such as:

*

*Docker Swarm: Docker Swarm is a container orchestrator provided by Docker, Inc. It is part of Docker Engine.

*Kubernetes: Kubernetes was started by Google, but now, it is a part of the Cloud Native Computing Foundation project.

*Mesos Marathon: Marathon is one of the frameworks to run containers at scale on Apache Mesos.

*Amazon ECS: Amazon EC2 Container Service (ECS) is a hosted service provided by AWS to run Docker containers at scale on its infrastructrue.

*Hashicorp Nomad: Nomad is the container orchestrator provided by HashiCorp.

A: Kubernetes is built on Docker technology. It is an orchestration tool for Docker container whereas Docker is a technology to create and deploy containers.
Docker, starting with a platform-as-a-service (PaaS) provider named dotCloud.
All in all, Kubernetes is related to the Docker container, allowing you to implement application portability and extensibility in container orchestration.
DOCKER
Easy and fast to install and configure
Functionality is provided and limited by the Docker API
Quick container deployment and scaling even in very large clusters
Automated internal load balancing through any node in the cluster
Simple shared local volumes
Kubernetes
Require some work to get up and running
Client, API and YAML definitions are unique to Kubernetes
Provides strong guarantees to cluster states at the expense of speed
To Enable load balancing requires manual service configuration
Volumes shared within pods
This is just a basic idea which at least explains the difference.If you want to go in depth see my posts
http://www.thecreativedev.com/an-introduction-to-kubernetes/
http://www.thecreativedev.com/learn-docker-works/

A: Docker and Kubernetes are complementary. Docker provides an open standard for packaging and distributing containerized applications, while Kubernetes provides for the orchestration and management of distributed, containerized applications created with Docker. In other words, Kubernetes provides the infrastructure needed to deploy and run applications built with Docker.


text:
Q: Сложный sql-запрос Есть таблица, куда записываются выплаты. Структура такая:
bill_id|owner_id|bill_first_name
owner_id - ID продавца
bill_first_name - имя клиента

Для того, чтобы выбрать все выплаты текущего продавца, можно просто:
SELECT * FROM bills AS bill WHERE bill.owner_id=5 GROUP BY bill.bill_first_name

Для того, чтобы получить количество уникальных bill_first_name для каждого owner_id, нужно нечто похожее на
SELECT COUNT(*) AS count FROM bills AS bill WHERE bill.owner_id=58 GROUP BY bill.bill_first_name

Но получается где-то так:
1
4
5
5

Как мне получить количество записей после такого запроса (не сумму!), в данном случае 4?

A: По-моему Ваше GROUP BY здесь не нужен.
Select count(distinct bill_first_name) from  bills were owner_id=58);
Тоже давно это было, но помнится, что count(distinct... )- было допустимо.
A: давно с мускулом не баловался, но может что-то типо этого:
SELECT COUNT(*) FROM (SELECT COUNT(*) AS count FROM bills AS bill WHERE bill.owner_id=58 GROUP BY bill.bill_first_name)


text:
Q: Solr facet.query for query, without filter.query Is there any way to get facet.query results only for the main query, without a facet.filter query.
For example, I have the request:
q=item_id:*
&fq=item_param:3
&facet.query=item_param:1
&facet.query=item_param:2

Is it possible to get facets from all item results (item_id:*), not from fq (item_param:3)?

A: This can be done by tagging and excluding filters. First, you want to tag your filter queries with a tag (e.g., filters):
fq={!tag=filters}item_param:3

Second, tell your facet queries to ignore the tag you used for the filters:
facet.query={!ex=filters}item_param:1
facet.query={!ex=filters}item_param:2


text:
Q: How to load and read excel file in python flask form post api Hi I want to upload a excel file form fronted and in back end i want to read all contents of that Excel File and store that in my database
@app.route('/getfile', methods=['POST'])
def getfile():
try:
   file = request.files['file']
   foo=file.filename
   dframe = pd.read_excel(foo)
   return dframe

except Exception as ex:
      return ex

i am getting filename and from panda i want to read that excel file data but its showing no such directory exists
from flask import Flask, request, jsonify
import flask_excel as excel
app = Flask(__name__)
import json
import xlrd
import os
import pandas as pd
from collections import OrderedDict
from pathlib import Path
from flask_cors import CORS,cross_origin
from json import loads
import pandas as pd

wsgi_app = app.wsgi_app
excel.init_excel(app)

code 1
@app.route("/upload", methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
    foo = request.get_array(field_name='file')
    # data = json.dumps(foo, )
    # for i in data[1:]:

     return jsonify({"result":foo })

#code 2
@app.route('/getfile', methods=['POST'])
def getfile():
try:
   file = request.files['file']
   foo=file.filename
   dframe = pd.read_excel(foo)
   return dframe

except Exception as ex:
      return ex

1st code giving me 404 exception and 2nd code giving me "No such Directory exits"
can anybody help me out in this reading the content of excel file

A: from flask import Flask, request, jsonify
from tablib import Dataset

app = Flask(__name__)

@app.route('/upload', methods=['POST'])
def upload_file():
    # I used form data type which means there is a
    # "Content-Type: application/x-www-form-urlencoded"
    # header in my request
    raw_data = request.files['myfile'].read()  # In form data, I used "myfile" as key.
    dataset = Dataset().load(raw_data)
    return jsonify(dataset.export('json'))

if __name__ == '__main__':
    app.run(debug=True)

This little snippet is working just fine. You don't need to use a huge data analyzing library to import something to database. But if you insist using pandas, your question needs another answer.
Check out the documentation before doing anything else:
http://flask.pocoo.org/docs/1.0/patterns/fileuploads/
http://docs.python-tablib.org/en/master/tutorial/#importing-data

A: Try this buddy, you need to read the file first (foo.read()). That way you'll get the un-parsed file, then you need to read this un-parsed file using pandas, like as follows:
@app.route('/getfile', methods=['POST'])
def getfile():
try:
    file = request.files['file']
    foo=file.filename
    unparsedFile = foo.read()
    dframe = pd.read_excel(unparsedFile)
    return dframe
except Exception as ex:
    return ex


text:
Q: Openshift PHP7 wordpress app throws "404 Page not found error" with custom domain name I have a wordpress app based on PHP7 catridge on Openshift. I added two alias to the app(e.g, www.xyz.com & xyz.com) and I also updated the CName in my Zone file. When I enter www.xyz.com, it redirects me to www.xyz.com/app and throws a 404 NOT FOUND error (nginx/1.11.6).
But I can access the administration page without any problem (www.xyz.com/wp-admin)
Can anyone please help?

A: Enter the www.domain.abc first. Use CloudFlare to configure your domain. Make things pretty easy.
After this you will get the pretty permalinks error related to ngnix.
I am too getting the same error. I can access the home page and most of the things. This error only arises when I decide to use Pretty Permalinks in WordPress.
Till now I have figured it out that we have to edit the ngnix file. But there are several files out there.
Has made me even more confused.
This may not be the solution but you can access post and other stuff in plain permalinks.


text:
Q: Django floppyforms OSMPointWidget does not display a map I am trying to put an OSM-map, similar to the one in the geodjango-admin, into a form on my main site.
I decided to use floppyforms, set everything up like in the documentation and it seems to get recognized, but strangely the map does not appear. Firebug shows that there is just an empty

 instead of the map, but it has all the right dimensions. The debug-textbox and the "Delete all features"-link are there like they should be. But, when I open the site, Firebug does not show any javascript requests in the 'network'-tab, so maybe that is a hint.
I guess I missed something or something isn't correctly included, but I tried for hours and really don't know anymore. Amongst other things I set all the paths for static files and run manage.py collectstatic, I also tried to not use the generic edit views, but it came out the same.
Here are the relevant parts in the code:
#views.py

import floppyforms as forms

...
class OSMPointWidget(forms.gis.PointWidget, forms.gis.BaseOsmWidget):
    pass

class LocationCreateView(CreateView):
    model = Location
    fields = ['name', 'zip', 'coord']
    form_class =  modelform_factory(Location,
        widgets={"coord": forms.gis.PointWidget(attrs = {
            'display_wkt': True,
            'map_srid':  4326,
            'map_width': 700,
            'map_height': 500,})})

#models.py

class Location(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField(max_length=255, blank=True, default='', unique=True)
    coord = models.PointField()
    zip = models.CharField(max_length=5, default='12345')
    objects = models.GeoManager()

    def __unicode__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super(Location, self).save(*args, **kwargs)

#urls.py

urlpatterns = patterns('',
    ...
    url(r"location/$", views.LocationCreateView.as_view(),
        name = "locationcreate"),
    ...
)

#location_form.html

{% extends "_layouts/base.html" %}
{% block page_title %}Enter Location | {% endblock %}
{% block page_content %}
    <form action="" method="post">
    {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Submit" />
    </form>
{% endblock %}

#base.html

<!doctype html>

        <title>{% block page_title %}{% endblock %}Calendar</title>
        <link rel="stylesheet" href="{{ STATIC_URL }}css/bootstrap.css">
        <link rel="stylesheet" href="{{ STATIC_URL }}css/bootstrap-theme.css" >

EVENTCALENDAR

                {% block page_content %}{% endblock %}

A: I just had a similar issue and realised that I needed to include a {{ form.media }} tag in the header and then django-floppyforms supplies the relevant javascript files to make the map magically appear.
Somewhere in the head of base.html include a block for extra javascript
{% block extra_js %}{% endblock %}

Then fill in the block in your location_form.html
{% block extra_js %}
{{ form.media }}
{% endblock %}


text:
Q: Is there a command for windows PE to capture system specs? Is there a command for windows PE to capture system specs? I am looking to make a Windows PE script to capture the systems specs and import them to a xls file.

A: The systeminfo command.  For example:
systeminfo /fo csv >specifications.csv


text:
Q: Passing a struct pointer as paramater in C# I need to include a .dll which contains the following C/C++ function prototype and struct definition:
typedef struct
{
    unsigned short us1;
    unsigned short us2;
    unsigned short data[16];
} myStruct;
int myFunc(myStruct *MYSTRUCT);

To use this Function i created a new Class:
static class DLL
{
public struct MyStruct
    {
     public ushort us1;
     public ushort us2;
     public ushort[] data;
     public PDPORT(ushort[] temp1, ushort temp2, ushort temp3)
     {
         us1 = temp2;
         us2 = temp3;
         data = temp1;
     }
    };
    [DllImport("PDL65DLL.dll")]
    public static extern int mvb_PutPort(ref MyStruct CommData);
}

In my main class I initiliaze the struct variable and call the Function like that:
    DLL.MyStruct communicationData = new DLL.MyStruct(new ushort[16], new ushort(), new ushort());
             DLL.MyFunc( ref communicationData);

However, this does not seem to work. The Function is passing something but not the right values, I suggest it is something with the pointer usage. Maybe a struct* is not the same as ref struct... Can someone explain what the problem is?

A: You might need to specify the packing of the struct (depending on the default packing used by the C++ code). You can also specify a fixed-sized array for the marshalling to take care of using [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)].
You also don't need the C# implementation to use a struct and indeed for the fairly large size of the data I would recommend using a class.
Here's an example:
[StructLayout(LayoutKind.Sequential, Pack=4)]
public sealed class MyStruct
{
    public ushort   us1;
    public ushort   us2;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    public ushort[] data;

    public MyStruct(ushort[] temp1, ushort temp2, ushort temp3)
    {
        us1  = temp2;
        us2  = temp3;
        data = new ushort[16];
        Array.Copy(temp1, data, Math.Min(temp1.Length, data.Length));
    }
}

Note how the constructor ensures that the size of the array is correct. You must always ensure that the size of the array matches the SizeConst declaration.
With these changes, the Marshaller should take care of things for you.

A: The C/C++ struct is more like a "fixed buffer":
    unsafe struct MyStruct
    {
        ushort us1, us2;
        fixed ushort data[16];
    }

This is not the same as an array, and is a little more awkward to work with in the C# code, but: it is possible.
I'm not 100% sure, but I believe you should also use an unmanaged pointer in the P/Invoke layer:
public static extern int mvb_PutPort(MyStruct* CommData);

which means you need to call it via:
fixed (MyStruct* ptr = whateverYouWereGoingToPass)
{
    mvb_PutPort(ptr);
}


text:
Q: How to display a text file whose first line is displayed in uppercase, while the remaining lines are unchanged tr a-z A-Z < items.txt
The above command can convert the text file to UPPER CASE, but I want the command that converts the first line only, leaving the other lines untouched.

A: Both of the commands given in the comments work.
Shawn's solution:
$ echo -e 'one\ntwo\nthree' | sed '1s/.*/\U&/'
ONE
two
three

glenn jackman's solution:
$ echo -e 'one\ntwo\nthree' | awk 'NR == 1 {$0 = toupper($0)} 1'
ONE
two
three

A: in awk, rule #1 is that don't split unnecessary fields :
echo -e "one alpha apple\ntwo beta"    \
        " orange\nthree omicron durian" |

{m,g}awk -F'^$' 'NF<NR || $_=toupper($_)'

ONE ALPHA APPLE
two beta orange
three omicron durian


text:
Q: Problem sending email using ssmtp I am attempting to setup so I can mail from Raspbian.
When I attempt to send I get an error ssmtp: Cannot open smtp.gmail.com:587 (I also tried port:465)
I have set "Access for less secure apps" on Google and can send/receive from the account on Thunderbird.
I have installed ssmtp and configured /etc/ssmtp/ssmtp.conf to contain:-
# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
root=xxxxxx.raspberry.pi@gmail.com

# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named mail.domain.com
mailhub=smtp.gmail.com:587

AuthUser=xxxxxx.raspberry.pi@gmail.com
AuthPass=xxxxxxxxxxxxxx
UseTLS=YES
UseSTARTTLS=YES

# Where will the mail seem to come from?
rewriteDomain=gmail.com

# The full hostname
hostname=xxxxxx.raspberry.pi@gmail.com

# Are users allowed to set their own From: address?
# YES - Allow the user to specify their own From: address
# NO - Use the system generated From: address
FromLineOverride=YES

I have also configured /etc/ssmtp/revaliases to contain:-
# sSMTP aliases
#
# Format:   local_account:outgoing_address:mailhub
#
# Example: root:your_login@your.domain:mailhub.your.domain[:port]
# where [:port] is an optional port number that defaults to 25.
root:xxxxxx.raspberry.pi@gmail.com:smtp.gmail.com:587

Any suggestions?

Edit
The settings above based on  https://wiki.archlinux.org/index.php/SSMTP
I have done some further testing.

*

*I selected a different SMTP server, which worked. (I do not want to use this, as it is only available when directly connected to my ISP.)

*I tried setting an Application Specific password, and got the response"The setting you are looking for is not available for your account". (Presumably because this account does not have 2-factor authentication.)
The gmail account I am trying to use was specifically created to send messages from the Raspberry Pi.

A: This is very easy to accomplish:
 https://unix.stackexchange.com/questions/363814/simplest-way-to-send-one-line-mail-out-via-command-line-using-gmail/363815#363815

EXCERPT:
Install ssmtp with the following commands:
sudo apt-get update
sudo apt-get install ssmtp

Then go into '/etc/ssmtp' and edit 'ssmtp.conf' to look like this:
root=rpi3abc@gmail
mailhub=smtp.gmail.com:465
FromLineOverride=YES
AuthUser=rpi3abc@gmail.com
AuthPass=testing123
UseTLS=YES

Send a one-liner like so:
echo "Testing...1...2...3" | ssmtp myusername@gmail.com

Couldn't be simpler.

A: The hostname assignment looks wrong. You probably want hostname=raspberry.pi or something like that. (Ideally, your host has a public DNS name, and you should use that.)  It should not be an email address.


text:
Q: Move files to more than one folder using python I am trying to move files from one folder to a different folder and below is my code.
import os, shutil

path = "C:\\Users\\mypath"
moveto = "C:\\Users\\mypath1" # Moving to this folder after upload

files = os.listdir(path)
files.sort()
for f in files:
    src = path+f
    dst = moveto+f
    shutil.move(src,dst)

Is there a way I can move the same files to one additional folder as well so that I have two copies of the documents.

A: You could append all of your destination directories to a list, and then iterate through the list on each copy. This way you could have 1 -> N number of directories to copy to.
import os, shutil

path = "C:\\Users\\mypath"
moveToPaths = ["C:\\Users\\mypath1", "C:\\Users\\mypath2"] # Moving to this folder after upload

files = os.listdir(path)
files.sort()
for f in files:
    src = path+f
    for moveToPath in moveToPaths:
        dst = moveToPath+f
        shutil.copy(src,dst)
shutil.rmtree(path)


text:
Q: add trailing slash to 404 url so it can be redirected Situation: moved old WordPress site to new domain; same permalink structure, 301'd $1
Shortly before the move, the tags had been cleaned up; reduced from over 2000 tags to a dozen or so tags; altho the tags were merged on-site, obviously, lots of 404's began as many of those old tags had been used on the site for years and widely indexed all over the internet.

*

*i.e. (/tag/frank-sinatra/ or /tag/tony-bennett/ merged and redirected to /tag/singers/)

I have been redirecting 404's as they occur via a combination of 404 Redirected Plugin http://wordpress.org/extend/plugins/404-redirected/ (logs and allows to create redirections), Google Webmaster Tools data (reports 404's / crawl errors...), Broken Link Checker http://wordpress.org/extend/plugins/broken-link-checker/ and adding redirects and mod_rewrites to my htaccess as each solution seems most economical.
My permalink / canonical url structure (/%postname%/) uses a trailing slash, ie. /post-or-page-name/ or /tag/tag-name/ or /category/category-name/
That said, here is a problem I am presented with that I have been unable to solve myself with a redirection / mod_rewrite regex:
Wordpress automatically redirects pages, posts, tags, categories missing the trailing trailing slash and I have created a considerable number of redirections BUT from the old tags to the new tags but lately I have encountered a slew of 404's for old tag url requests that are missing the trailing slash, most of which I have already fixed as urls with a trailing slash. i.e.

*

*/tag/frank-sinatra/ 301 --> /tag/singers/ = 200 Success

*/tag/frank-sinatra = 404 Not Found

They are being 404'd before a trailing slash can be forced to the end of the url so they can be redirected
Is there a solution for this other than creating individual 301's for each old tag url missing the trailing slash?
I have to believe this must be a pretty common problem but the work smart solution has eluded me so far!
Thanks those more knowledgeable than myself and generous enough to share a solution :)

A: If all of your URLs end in a trailing slash, then one way to address this is to redirect those that do not have one. This will result in 2 301's, but that is better than a 404.
To do this add the following to the .htaccess file in the root directory of your site. Make sure these rules appear before other existing rules.
RewriteEngine on
RewriteBase /

#if not an existing file
RewriteCond %{REQUEST_FILENAME} !-f
#redirect urls without a trailing slash
RewriteRule ^(.*[^/])$ $1/ [L,R=301]

If the URLs missing a trailing slash are all tag URLs, then change the last rule to
RewriteRule ^(tag/.*[^/])$ $1/ [L,R=301]

A: Another way to do this is to use a ? in your individual redirects to make the trailing slash optional.
RewriteRule ^/tag/frank-sinatra/?$ /tag/singers/


text:
Q: Sending Image in email with text retrieved from DB Currently we stored email text in db table and when we send an email, we query the db get the email text, do an HTML Encode and send email. But now we need to send Images in the email. What I did was stored the image in project file and stored the image location as tag in email text in db table. But its not working, any ideas on how should i do this. I need to insert image in middle of text. This is how we store html email in db table. As html is being parsed I copied it in comments section.

A: Pass your body to an html form and allowhtml(true) while sending email like this
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient();
                SmtpServer.Host = Host;
                mail.IsBodyHtml = true;
                mail.From = new MailAddress(FromEmail);
                mail.To.Add(ToEmail);
                mail.Body = MailBody;

such that MailBody is String.Format("{0} with < img href='{1}' />",email,imagesrc);
{0} will be replaced by email
{1} will be replaced by imagesrc

A: you have to upload your picture to a webserver and set the src of the image to the absolute path!
<img src="http://www.myuploaded.com/image.jpg" />

if you cannot do that look at this post:
how to embed image in email


text:
Q: necessary and sufficient conditions for the following inequality to be hold Let $p=(p_n)$ is a sequence of nonnegative numbers with $p_0>0$ s.t
$P_n= \sum_{k=0}^{n}p_k \rightarrow \infty$ as $n \rightarrow \infty$ and let $t\in(0,1)$.
find necessary and sufficient conditions for the following inequality to be hold
$\displaystyle  \left|   k \frac{p_k}{P_{k-1}}- (k+1)\frac{p_{k+1}}{P_{k}}t \right| \leq C k (1-t)$   (C:constant)


text:
Q: Update lat and long when the mapview camera is being moved? Here's my code, that works but it doesn't get updated and it's not accurate. I simply want to apply the camera lat and lng to another variable.
let cameraLat = self.mapView.camera.centerCoordinate.latitude
let cameraLng = self.mapView.camera.centerCoordinate.longitude

A: for google maps:
if you have set the mapView.delegate = self and you have implemented the GMSMapViewDelegate it's pretty easy to get the an event everytime the camera changes, so you mapView view changes.
you could either implement the func mapView(mapView: GMSMapView, didChangeCameraPosition position: GMSCameraPosition) or func mapView(mapView: GMSMapView, idleAtCameraPosition position: GMSCameraPosition) method.
and then access the new camera values (lat/lng) like you did before, so just reassign your variables to the new values.
or MapKit:
add delegate to class like
class ViewController: UIViewController, MKMapViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        ...
        mapView.delegate = self
    }
}

This method is called whenever the currently displayed map region changes. During scrolling, this method may be called many times to report updates to the map position. Therefore, your implementation of this method should be as lightweight as possible to avoid affecting scrolling performance.

func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
   let lat = mapView.camera.centerCoordinate.latitude
   let lng = mapView.camera.centerCoordinate.longitude
}


text:
Q: Pass an email address to the SendObject method in VBA I would like to take the email address from my table 'GetContact_TempTbl" and send the report to that email address. This email will change according the company that recieves. I currently pull the related email address and store it in the temporary table. I currently get the Object Required error.
Many thanks in advace for the advice.
Dim db As Database
Dim rs As Recordset
Dim stRecipients As String
Dim stDocName As String

Set db = CurrentDb()
Set rs = db.OpenRecordset("GetContact_TempTbl")
Set stRecipients = rs.Fields("Contact_Email")
stDocName = "License CODs"
stRecipietns = stRecipients

DoCmd.SendObject acReport, stDocName, acFormatPDF, stRecipients, , , "Thank You for your purchase"

A: You should only use set with an object, not a string:
Dim db As Database
Dim rs As Recordset
Dim stRecipients As String
Dim stDocName As String

Set db = CurrentDb()
Set rs = db.OpenRecordset("GetContact_TempTbl")
''This is not a field object, it is a string
stRecipients = rs.Fields("Contact_Email")
stDocName = "License CODs"
stRecipietns = stRecipients

DoCmd.SendObject acReport, stDocName, acFormatPDF, _
   stRecipients, , , "Thank You for your purchase"

It may be possible to make this easier if you say how you create the temporary table.

A: If your recordset holds one row for each recipient you want to email, walk the recordset to gather them instead of reading only the recipient from the first row.
Const stDocName As String = "License CODs"
Dim db As DAO.database
Dim rs As DAO.Recordset
Dim stRecipients As String

Set db = CurrentDb()
Set rs = db.OpenRecordset("GetContact_TempTbl")
With rs
    Do While Not .EOF
        stRecipients = stRecipients & ";" & !Contact_Email
        .MoveNext
    Loop
    .Close
End With

If Len(stRecipients) > 0 Then
    ' discard leading ";"
    stRecipients = Mid(stRecipients, 2)
    DoCmd.SendObject acReport, stDocName, acFormatPDF, _
        stRecipients, , , "Thank You for your purchase"
Else
    MsgBox "No recipients to email!"
End If

Set rs = Nothing
Set db = Nothing

However, if my interpretation was incorrect, and the recordset always contains a single row with just one Contact_Email, you don't even need a recordset.  You can simply retrieve the Contact_Email with DLookup.
stRecipients = Nz(DLookup("Contact_Email", "GetContact_TempTbl"), "")


text:
Q: Undefined method 'click' for nil:NilClass (Mechanize) I am building a script using Mechanize to scrape data from a website. The script is supposed to click on the "Read biography" link and then scrape the biography of the member on the next page.
Here is the script in the Rake file:
require 'mechanize'
require 'date'
require 'json'

task :testing2 do

    agent = Mechanize.new
    page = agent.get("https://www.congress.gov/members")

    page_links = page.links_with(href: %r{.*/member/\w+})

    member_links = page_links[0...2]

    members = member_links.map do |link|

      member = link.click

      name = member.search('title').text.split('|')[0]
      institution = member.search('td~ td+ td').text.split(':')[0]
      dob = member.search('.birthdate').text.strip[1..4]

      # Get bio
      bio_link = member.link_with(:text => 'Read biography').click
      bio = bio_page.search('p').text.strip

      {
        name: name.strip,
        institution: institution.strip,
        dob: dob,
        bio: bio

      }

    end

    puts JSON.pretty_generate(members)

end

A: There are two calls to click:
member = link.click

and
bio_link = member.link_with(:text => 'Read biography').click

The first is called on iterator, that can not be nil, hence the problematic one is the second.
Try to put debug output, or set a breakpoint before # Get bio and examine what's wrong with it. It is impossible to say why member.link_with(:text => 'Read biography') returns nil by the information you have provided.

A: The code you are using:
member.link_with(text: 'Read biography')

does not find the link, because the link has some space and new lines characters in it. You need to use it like this:
member.link_with(text: /Read biography/)

that code will find the link.


text:
Q: ASP.NET MVC Server-Side Paging (From WCF Service) Currently I am using ASP.NET MVC 4 and jqGrid with server-side paging. The issue I am facing is that the data source come from a third-party web service and I need to implement server-side paging over the result retrieved from the above-mentioned service. Since I should follow the stateless nature of MVC, I am a bit reluctant to use Session or Cache. Your suggestions is much appreciated!

A: *

*Check if your service provider is supporting OData. If yes, then you
need to look at it and it solves your question on completely
different way.

*Cache and Session do not exist in the same context. Session is bound
to a single user, while Cache is shared for all users. It really
depends whether the data coming from the web service is unique to
each user or it is all the same for everyone. If it is the same,
then cache is optimal as using session in that case would just eat
your server memory with duplicate data.

*If your data is not in extremely large amounts, you might even store
it on client-side by rendering table and then using table2grid
provided by jqGrid.


text:
Q: Passing arguments to executable pinned in Taskbar I try to add --enable-vertical-tabs to the Chrome shortcut/pin in my Windows7 Taskbar.
Like indicated here https://superuser.com/a/234287 I edited properties of the shortcut. In the end the target is: "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe -enable-vertical-tabs"
However Windows7 doesn't allow me for such a target:
[Window Title]
Problem with Shortcut

[Content]
The name 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe --enable-vertical-tabs'
specified in the Target box is not valid.
Make sure the path and file name are correct.

[OK]

Any idea how can I pass arguments to the executables pinned in Taskbar ?

A: Source A list of useful Google Chrome command line switches

If you are starting Google Chrome from a shortcut, placed on the
  desktop, taskbar or start menu, then you can easily add command line
  switches to it.  Just right-click the shortcut, locate Google Chrome
  there, right-click on it and select Properties.
The Shortcut tab should open up automatically. It displays the load
  path of the browser in the target field. At the end of the field,
  after the closing ", add a space, and then the command line switches
  you want to use.
Add another space between each command line switch if you want to use
  multiple ones.

Your shortcut is malformed. You have:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe -enable-vertical-tabs"

The options to chrome should be outside of the "s:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --enable-vertical-tabs

Note also the option should be --enable-vertical-tabs not -enable-vertical-tabs


text:
Q: suitescript 2.0 fail to evaluate I am a novice suitescript writer and cannot figure out what I am doing wrong.  I am trying to load a very simple suitescript 2.0 script to calculate values in a custom table.  I can upload the script file just fine but when I create the script record, I get the following error: Fail to evaluate script: {"type":"error.SuiteScriptModuleLoaderError","name":"UNEXPECTED_ERROR","message":"missing : after property id (SS_SCRIPT_FOR_METADATA#22)","stack":[]}
Here is the code
/**
 *@NApiVersion 2.x
 *@NScriptType ClientScript
 */
define(['N/currentRecord'],
    function fieldChanged(context) {
        var fieldName=context.currentRecord.fieldID;
    //return if not one of these fields
    if (fieldName!=='custrecord_am_ehir_emp_prem_percent' &&
    fieldName!=='custrecord_am_ehir_dep_prem_percent' &&
            fieldName!=='custrecord_am_ehir_total_month_prem')
            return false;
        else
            //get premium and percent values
        var totalPremium=currentRecord.getValue(
            {fieldID:'custrecord_am_ehir_total_month_prem'
            });
        var employeeOnlyPremium=currentRecord.getValue(
            {fieldID:'custrecord_am_ehir_emp_only_prem'
            });
        var employeePercent=currentRecord.getValue(
            {fieldID:'custrecord_am_ehir_emp_prem_percent'
            });
        var dependentPercent=currentRecord.getValue(
            {fieldID:'custrecord_am_ehir_dep_prem_percent'
            });
        var employeePremium=totalPremium*employeePercent;
        var dependentPremium=(to1talPremium-employeeOnlyPremium)*dependentPercent;
        var companyPremium=totalPremium-employeePremium-dependentPremium;
        //set field values
        currentRecord.setValue(
            {fieldID:'custrecord_am_ehir_emp_month_prem',employeePremium
            });
        currentRecord.setValue(
            {fieldID:'custrecord_am_ehir_dep_month_prem',dependentPremium
            });
        currentRecord.setValue(
            {fieldID:'custrecord_am_ehir_co_month_prem',companyPremium
            });
        return {fieldChanged:fieldChanged};
    }
);

A: Robert,
The property name is "fieldId" instead of "fieldID". I think that is causing the error.
Regards,
Luiz Morais

A: I saw some code error in your script

*

*Just like Luiz mention, change "fieldID" to "fieldId"

*there is a typo in line 30, "to1talPremium" I believe is "totalPremium"

*currentRecord.setValue function should follow with 2 argument {fieldId: '', value: ''}
currentRecord.setValue(
    {
        fieldId: 'custrecord_am_ehir_emp_month_prem', employeePremium
    });

This code will not work if you using SuiteScript 2.0
try this
currentRecord.setValue({
            fieldId: 'custrecord_am_ehir_emp_month_prem',
            value: employeePremium
        });

Let me know if you have more question.

A: I think  code  should  ↓

/**
 *@NApiVersion 2.x
 *@NScriptType ClientScript
 */
define(['N/currentRecord'],
function(currentRecord){
     function fieldChanged(context) {}
     return {fieldChanged:fieldChanged}
})

A: Your code had a few issues but the important one that caused Module Loader Error was

*

*You need to have curly-braces for multi-line scripts as follows
else {
  //get premium and percent values
  var totalPremium = currentRecord.getValue({
    fieldID: 'custrecord_am_ehir_total_month_prem'
  });
  var employeeOnlyPremium = currentRecord.getValue({
    fieldID: 'custrecord_am_ehir_emp_only_prem'
  });
  var employeePercent = currentRecord.getValue({
    fieldID: 'custrecord_am_ehir_emp_prem_percent'
  });
  var dependentPercent = currentRecord.getValue({
    fieldID: 'custrecord_am_ehir_dep_prem_percent'
  });
var employeePremium = totalPremium * employeePercent;
  var dependentPremium = (to1talPremium - employeeOnlyPremium) * dependentPercent;
  var companyPremium = totalPremium - employeePremium - dependentPremium;
//set field values
  currentRecord.setValue({
    fieldID: 'custrecord_am_ehir_emp_month_prem', employeePremium
  });
  currentRecord.setValue({
    fieldID: 'custrecord_am_ehir_dep_month_prem', dependentPremium
  });
  currentRecord.setValue({
    fieldID: 'custrecord_am_ehir_co_month_prem', companyPremium
  });
}

*It is fieldId and not fieldID or fieldid.
eg.
var totalPremium = currentRecord.getValue({
  fieldId: 'custrecord_am_ehir_total_month_prem'
});

*To set a value using SS2.0 you need to pass object containing 2 properties fieldId and value.

So, to set a value you need to do the following.
currentRecord.setValue({
  fieldId:'custrecord_am_ehir_emp_month_prem',
  value: employeePremium
});

For further readings, you can refer to Record Module in NetSuite Help


text:
Q: AngularJS promise hangs UI My app hangs even though I am using a promise to run calculations.
I'm writing a little BlackJack game in Angular. In this game, I want to display permutations of cards at the bottom of my game board. My game board renders fast when I don't call the getData() method (see below) that calculates the permutations. But when I call getData() my UI hangs.
The service where I declare and return a promise looks like this:
app.service('cardService', ['$q', 'myservice', 'calculation', function ($q,  myservice, calculation) {
    return {
        getData: function () {
            var defer = $q.defer();

            myservice.setup_deck();
            var cards = myservice.get_needed_cards(myservice.player_hand, myservice.static_deck);

            // This is calculation-intensive
            var dh_grouped = calculation.step1(cards);
            var result = calculation.step2(dh_grouped);

            defer.resolve(result);

            return defer.promise;
        }
    };

}]);

Now, I call the promise in a very vanilla way like this:
// controller.js
$scope.display_calculations = function () {

    cardService.getData().then(function(result){
        $scope.calcs = result;
        console.log('calculations successful');
    });
    console.log('this message shows before the one above');
};

// The relevant HTML
{{c.result}}

To debug, I removed the statement $scope.calcs = result to see if removing them would stop my UI from hanging:
cardService.getData().then(function(result){
    console.log('calculations successful');
});

The above did not work. My UI still hangs! The only way I could prevent the UI from hanging is by not calling getData().
How can I use angular so my expensive operations don't hang the UI?
P.S. I am using Angular 1.2.21 and even tried using 1.5.x but that did not work either.

A: You might be confusing promises with threads. Promises don't enable concurrent execution. If you need to perform CPU intensive tasks in JavaScript while keeping the UI responsive, you have to either:

*

*spawn a WebWorker (browsers)

*spawn a process (Node.js)

*find a way to split the computations into small chunks and run it chunk by chunk  (so the UI can respond to the user between each chunk)

A: Use $timeout
app.service('cardService', ['$q', '$timeout', 'myservice', 'calculation', function ($q,  $timeout, myservice, calculation) {
    return {
        getData: function () {
            return $timeout(function() {
               myservice.setup_deck();
               var cards = myservice.get_needed_cards(myservice.player_hand, myservice.static_deck);

               // This is calculation-intensive
               var dh_grouped = calculation.step1(cards);
               return calculation.step2(dh_grouped);
            }, 1);
        }
    };
}]);

This will defer the execution and let your UI load first. $timeout returns a promise so the rest of your code can stay the same.

A: I was working on a embedded system and didn't had GUI refresh issues at all but i was having hang outs while time to time instead (its a physical device so it stays turned on for days/months/years) as @DerekMT12 mentions adding $timeout fixed this behavior
Module
var myApp = angular.module('myApp',['ngRoute']);

Service
var yourServiceModule = myApp.service('YourService', function ($http) {
    this.your_method = function (a) { return a*a};
});

Controller
//just wrap your service,http call using $timeout
$timeout(function() {
    //vanilla service call
    YourService.your_method().then(
              function (response) {
                 //console.log("sync_with_cloud: "+ response);
                 $scope.check_cloud_port_statuses_progress=100;
                 //...
             },
              function(data) {
                  // Handle error here

                $rootScope.global_config_1 += "\nError(333): cant connect to cloud at "+Date.now();+"\n\n";
                $scope.check_cloud_port_statuses_progress = -1;
              }
    );

}, 8);