text:
Q: Valor de pico de um histograma Meu código lê uma imagem e faz a transformação do modelo de cores RGB para HSV, e depois faço um histograma de frequência de cada canal (H, S e V), sendo que H varia de 0-179 e os demais de 0-255. Com plotagem do histograma é possível verificar picos nos canais H, S e V. Esse histograma mostra através do eixo vertical a quantidade de pixels e do eixo horizontal os canais H ,S e V. Estou querendo retornar os valores de H, S e V em que a quantidade de pixels é maior, ou seja, o pico do histograma de cada canal. Como fazer isso? Já utilizei o método np.amax() mas ele me retorna os valores máximos de cada canal (H = 179, S = 255 e V =255).
def show_hsv_hist(image):
    # Hue
    plt.figure(figsize=(20, 3))
    histr0 = cv2.calcHist([hsv], [0], None, [180], [0, 180])
    plt.plot(histr0)
    plt.xlim([0, 180])
    plt.title('Hue')

    # Saturation
    plt.figure(figsize=(20, 3))
    histr1 = cv2.calcHist([hsv], [1], None, [255], [0, 255])
    plt.xlim([0, 255])
    plt.plot(histr1)
    plt.title('Saturation')

    # Value
    plt.figure(figsize=(20, 3))
    histr2 = cv2.calcHist([hsv], [2], None, [255], [0, 255])
    plt.xlim([0,255])
    plt.plot(histr2)
    plt.title('Value')

    max_v = np.amax(v)
    print (max_v)

A moda pode descobrir o valor mais frequente para cada canal. Tem algum método para isso? Sei que existe no numpy mediana, média.

A: O valor de Y máximo e X máximo podem ser encontrados com a função max() e numpy.where
ymax = max(histr)
xmax, _ = np.where(histr == ymax)

print(xmax, ymax)

Código
import cv2
import numpy as np
import urllib.request
import matplotlib.pyplot as plt

def show_hsv_hist(hsv):
    HSV = [['Hue', 0, 180], ['Saturation', 1, 255], ['Value', 2, 255]]
    for nome, canal, valor in HSV:
        # Gráfico
        plt.figure(figsize=(20, 3))
        hist = cv2.calcHist([hsv], [canal], None, [valor], [0, valor])
        plt.plot(hist)
        plt.xlim([0, valor])
        plt.title(nome)
        #Máximo
        ymax = max(hist)
        xmax, _ = np.where(hist == ymax)
        print(ymax, xmax)

resp = urllib.request.urlopen("https://upload.wikimedia.org/wikipedia/commons/3/32/Carrots_of_many_colors.jpg")
img = np.asarray(bytearray(resp.read()), dtype="uint8")
img = cv2.imdecode(img, cv2.IMREAD_COLOR)

cv2.imshow('Original', img)
cv2.waitKey(0)

hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

show_hsv_hist(hsv)
plt.show()


text:
Q: webpack-dev-server not running (ECONNREFUSED) I'm having some troubles with webpack, after some commits I tried to run the server but nothing appear at http://localhost:3000. The config seems OK and this already worked meanwhile. Any suggestions are welcome.
At webpack.config, I tried to use 127.0.0.1 instead localhost keyword and didn't worked. Also, changing http to https and didn't change to better.
The console output:
> webpack-dev-server --config webpack.config.js --mode development --hot

[HPM] Proxy created: [ '/' ]  ->  http://localhost:3000
ℹ 「wds」: Project is running at http://localhost:8085/
ℹ 「wds」: webpack output is served from /build
ℹ 「wds」: Content not from webpack is served from /build/
ℹ 「wds」: 404s will fallback to /index.html
[HPM] Error occurred while trying to proxy request / from localhost:8085 to http://localhost:3000 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)
[BABEL] Note: The code generator has deoptimised the styling of /node_modules/react-dom/cjs/react-dom.development.js as it exceeds the max of 500KB.
ℹ 「wdm」: Hash: 267d8ae083c789a0e40f
Version: webpack 4.44.2
Time: 12214ms
Built at: 03/27/2021 10:21:06 PM
            Asset      Size  Chunks             Chunk Names
     ./index.html   1.7 KiB          [emitted]
          dam.ico  66.1 KiB          [emitted]
webpack-bundle.js  3.05 MiB    main  [emitted]  main
Entrypoint main = webpack-bundle.js

The webpack.config.js :
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

const webpack = require("webpack");

module.exports = {
  entry: "./src/index.js",
  mode: "development",
  output: {
    path: path.resolve(__dirname, "build"),
    filename: "webpack-bundle.js",
    publicPath: path.resolve(__dirname, "/build/"),
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: "babel-loader",
        exclude: ["/node_modules/", "/src/styles.css"],
      },
      {
        test: /\.(css)$/,
        loaders: ["style-loader", "css-loader"],
      },
       {
        test: /\.(jpg|png)$/,
        use: {
          loader: 'url-loader',
        },
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./public/index.html",  // reference index.html file
      filename: "./index.html",         // the name and location of referenced file at output folder
      favicon: "public/dam.ico",
    }),
  ],
  devServer: {
    publicPath: path.resolve(__dirname, "/build/"),
    contentBase: "/build/",              // path that contain webpack-bundle
    port: 8085,                          // port where the app will be accessible
    hot: true,
    open: true,                          // open web browser after compiled
    historyApiFallback: true,
    proxy: [
      {
        context: ["/"],                  // endpoint which you want to proxy the provider
        target: "http://localhost:3000",     // your main server address - react app provider
      },
    ],
  },
};

The package.json:
{
  "name": "ediawater",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.11.2",
    "@react-google-maps/api": "^2.1.1",
    "@reduxjs/toolkit": "^1.5.0",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "axios": "^0.21.1",
    "bootstrap": "4.5.3",
    "google-map-react": "^2.1.9",
    "prop-types": "^15.7.2",
    "pubsub-js": "^1.9.3",
    "react": "17.0.0",
    "react-bootstrap": "1.4.0",
    "react-dom": "17.0.0",
    "react-grid-layout": "1.2.0",
    "react-json-to-csv": "^1.0.4",
    "react-laag": "^2.0.2",
    "react-redux": "^7.2.2",
    "react-scripts": "^4.0.1",
    "redux": "^4.0.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "dev-start": "webpack-dev-server --config webpack.config.js --mode development --hot",
    "dev-build": "webpack --config webpack.config.js"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/core": "^7.13.8",
    "@babel/plugin-proposal-class-properties": "^7.13.0",
    "@babel/plugin-syntax-dynamic-import": "^7.8.3",
    "@babel/preset-env": "^7.13.8",
    "@babel/preset-react": "^7.12.13",
    "css-loader": "^5.1.0",
    "eslint": "^7.17.0",
    "eslint-config-google": "^0.14.0",
    "eslint-config-standard": "^16.0.2",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-react": "^7.22.0",
    "prettier": "^2.2.1",
    "reactide-config": "^1.0.2",
    "style-loader": "^2.0.0",
    "url-loader": "^4.1.1",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.7.0"
  }
}

A: If you setup a proxy in the config, you (the dev) are expected to run a server where things are being proxied to e.g at http://localhost:3000. Webpack devserver does not create the proxied server for you. The proxy setting is commonly used to proxy api calls e.g
    proxy: {
      '/api': 'http://localhost:3000',
    },

So if you do not have a reason to proxy, e.g an api, remove the proxy settings and use the devserver port e.g localhost:8085.
More info in the docs.
Also the contentBase should be an absolute path.

redpajama_set_name: RedPajamaStackExchange


text:
Q: LayoutInflater не понимает CheckedLinearLayout У меня есть класс CheckableLinearLayout:
public class CheckableLinearLayout extends LinearLayout implements Checkable {
    private static final int[] CHECKED_STATE_SET = {android.R.attr.state_checked};

    private boolean mChecked = false;

    public CheckableLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public boolean isChecked() {
        return mChecked;
    }

    public void setChecked(boolean b) {
        if (b != mChecked) {
            mChecked = b;
            refreshDrawableState();
        }
    }

    public void toggle() {
        setChecked(!mChecked);
    }

    @Override
    public int[] onCreateDrawableState(int extraSpace) {
        final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
        if (isChecked()) {
            mergeDrawableStates(drawableState, CHECKED_STATE_SET);
        }
        return drawableState;
    }

Я его использую в layout'e вместо LinearLayout. При попытке заинфлейтировать этот layout через View convertView = mInflater.inflate(R.layout.row_words_form_1, null, true);, выскакивает ошибка:
Вот stacktrace:
android.view.InflateException: Binary XML file line #9: Error inflating class <unknown>
        at android.view.LayoutInflater.createView(LayoutInflater.java:613)
        at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:660)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
        at com.dugin_rostislav.dictionary.CustomListAdapter_Words.getView(CustomListAdapter_Words.java:46)
        at android.widget.AbsListView.obtainView(AbsListView.java:2159)
        at android.widget.ListView.makeAndAddView(ListView.java:1831)
        at android.widget.ListView.fillDown(ListView.java:674)
        at android.widget.ListView.fillFromTop(ListView.java:735)
        at android.widget.ListView.layoutChildren(ListView.java:1652)
        at android.widget.AbsListView.onLayout(AbsListView.java:1994)
        at android.view.View.layout(View.java:14008)
        at android.view.ViewGroup.layout(ViewGroup.java:4373)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1663)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1521)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
        at android.view.View.layout(View.java:14008)
        at android.view.ViewGroup.layout(ViewGroup.java:4373)
        at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1627)
        at android.view.View.layout(View.java:14008)
        at android.view.ViewGroup.layout(ViewGroup.java:4373)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1663)
        at android.widget.LinearLayout.layoutHorizontal(LinearLayout.java:1652)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1436)
        at android.view.View.layout(View.java:14008)
        at android.view.ViewGroup.layout(ViewGroup.java:4373)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1663)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1521)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
        at android.view.View.layout(View.java:14008)
        at android.view.ViewGroup.layout(ViewGroup.java:4373)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
        at android.view.View.layout(View.java:14008)
        at android.view.ViewGroup.layout(ViewGroup.java:4373)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1663)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1521)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
        at android.view.View.layout(View.java:14008)
        at android.view.ViewGroup.layout(ViewGroup.java:4373)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
        at android.view.View.layout(View.java:14008)
        at android.view.ViewGroup.layout(ViewGroup.java:4373)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1892)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1711)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
        at android.view.Choreographer.doCallbacks(Choreographer.java:562)
        at android.view.Choreographer.doFrame(Choreographer.java:532)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
        at android.os.Handler.handleCallback(Handler.java:725)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5041)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.reflect.InvocationTargetExce

.xml разметка:
    <?xml version="1.0" encoding="utf-8"?>
<com.dugin_rostislav.dictionary.CheckableLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
    android:id="@+id/linearLayout_1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/black" >

    <TextView
        android:id="@+id/text_1"
        android:background="@drawable/text_view_background_one"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="8"
        android:layout_marginBottom="0.5dp"
        android:duplicateParentState="true" />

    <TextView
        android:id="@+id/text_2"
        android:background="@drawable/text_view_background_one"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="46"
        android:layout_marginLeft="0.5dp"
        android:layout_marginBottom="0.5dp"
        android:duplicateParentState="true" />

    <TextView
        android:id="@+id/text_3"
        android:background="@drawable/text_view_background_one"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="46"
        android:layout_marginLeft="0.5dp"
        android:layout_marginBottom="0.5dp"
        android:duplicateParentState="true" />
</com.dugin_rostislav.dictionary.CheckableLinearLayout>

A: Укажите в разметке полное имя класса, включая имя пакета
<my.package.subpackage.CheckableLinearLayout ...


text:
Q: comparing each value in a dictionary to each other value I am trying to write a python code that would compare each value in a dictionary to each other value. For example:
dict={key1:[values1],key2:[values2],key3:[values3}.

I would like to compare each value with each other value. i.e. value1 with value2, value1 with value3,  value2 with value3.

A: is this what your looking for?
for k in topology:
    for j in topology:
        if k == j:
            continue
        else:
            # compare values at key k and key j
            my_compare_function(topology[k], topology[j])

A: You can use itertools.combinations to create all pairs. Here is a trivial example:
from itertools import combinations
# create an example dictionary
dict = {"a": 1, "b": 2, "c": 2}
# generate all pairs
all_pairs = list(combinations(dict.items(), r = 2))
# create mapping of comparisons of the values of each pair
{pair:pair[0][1] == pair[1][1] for pair in all_pairs}

Output:
(('c', 2), ('b', 2)): True, (('a', 1), ('b', 2)): False, (('a', 1), ('c', 2)): False}


text:
Q: Why is Stack Overflow discouraging "which book should I read for..." questions? Maybe this is not such a stupid question. There are similars, but they don't directly answer what I'm asking:

*

*Aren't questions about "best" going to end up having answers reflecting only popularity?

*How to request book recommendations
So, watching the second answer, can I actually post something like "What's your favourite book to learn Objective-C?" (for example)
I'm asking this because I think that programmers actually have hard times finding good books (they cost a lot) and sharing this knowledge with others is sure a good idea (expecially for the wallet).
Now these questions are getting closed more often, but still I think that Stack Overflow is the main place where I should look for when I'm going to buy new programming books.
Are there any "formula" that allows me to get some suggestions about which book should I buy, such as "Which is the most popular book to learn Objective-C"?
And finally, why are book-questions discouraged on this website (expecially programming books) when even if they are subjective all the questions ends up in having an answer with a lot of upvotes making the answer quite explicit in such case.
I think that Stack Overflow is a place where you share knowledge and not talking about books (source of knowledge) is a bad idea. I think it's not a random situation that all questions about books are heavily visited/voted/discussed. I think it's an important signal from the community that is saying "we are interested in this!"
Edit 1:
I'm having a lot of comments, so I post some updates here:
Is a valid question *What's the most popular book for Stack Overflow users to learn XXX?". Obviusly the book should be related to programming (like a programming language).

A: I think this is a great idea, we could expand it to what blogs are the best, which movies relating to Computer Science are the best, which podcasts are the best, which languages are the best, which frameworks are the best, which plugins for frameworks are the best, which spacing and indentation style are the best, how many characters per line are the best, and which NGO's help you learn the most about programming. Probably even which college is the best if we're forward-thinking enough.
We could be the Angie's List of Programming!
...or not.
The Q&A format of Stack Exchange does not lend itself well to "Best Of" lists or really any discussion where there never could be an objective answer. (Ab)using SO to provide a place to find good programming books is a bad idea, as SO does a bad job of being a place to find lists of anything. It just wasn't built to do this effectively.
"Best Of" lists, for say books, are best on sites that handle those sorts of things. In your case, this would be retailers like Barnes and Noble, Amazon, or Online Sales Presence X.


text:
Q: Why doesn't changing the data point value(s) updates the value in backend excel of a ppt chart? I stumbled onto something very interesting. So I have two charts. They have the same series names but different data. Using the below code, I replaced all the values of the data points of first chart with the values in second chart. On the front end the code seemed to have worked perfectly. All the data points in first chart now reflects the change. But interestingly enough, if I open the backend excel of first chart, it still has the old values. The change was reflected only in the front end, not in backend.
Can anybody explain to me why is this so and is there any method by which I can force the chart's embedded excel to take on values that it's data points shows.
   For trial_a = 1 To thischart.FullSeriesCollection.count
          For trial_b = 1 To thatchart.FullSeriesCollection.count
              If thischart.FullSeriesCollection(trial_a).Name = thatchart.FullSeriesCollection(trial_b).Name Then

                       thischart.FullSeriesCollection(trial_a).Values = thatchart.FullSeriesCollection(trial_b).Values
                       thischart.FullSeriesCollection(trial_a).XValues = thatchart.FullSeriesCollection(trial_b).XValues

              End If
           Next trial_b
   Next trial_a

A: I've been playing around with this since Jon Peltier pointed out that there is a way to get at the Workbook object. Check this out:
Sub CheckSelectedChart()

Dim oShp As Shape
Dim oChart As Chart
Dim oWorkbook As Workbook
Dim oActiveSheet As Worksheet

Set oShp = ActiveWindow.Selection.ShapeRange(1)
Set oChart = oShp.Chart
Set oWorkbook = oChart.ChartData.Workbook

' This is the step I was always missing!
oChart.ChartData.ActivateChartDataWindow

Set oActiveSheet = oWorkbook.ActiveSheet

Debug.Print "Break!"

End Sub

When I had explored this in the past, I got as far as inspecting the ChartData object that's part of the chart -- however, if you're just working with a normal chart selection, the Workbook object always looked empty (no Worksheets, etc.)
It turns out that you have to run the ActivateChartDataWindow method, which pops up the datasheet.
Once you do that, the Workbook object is populated, and you're able to assign the chart's data sheet to a Worksheet object and treat it like an Excel Worksheet, as far as I can see.
/edit Here is some more code to help store the source worksheet data and then input it into the destination worksheet, which more clearly gets at the problem you were trying to solve.
While I'm seeing that in your initial example you have some conditionals in there, where the data is only replaced if the series name matches, it should be pretty easy for you to adapt this example, where we copy the entire data table from one embedded chart to another:
' assign oActiveSheet to the underlying worksheet of the source chart.

With oActiveSheet.UsedRange
    rowCount = .Rows.Count
    columnCount = .Columns.Count

    ReDim dataArray(1 To rowCount, 1 To columnCount)

    For i = 1 To rowCount
        For j = 1 To columnCount
            dataArray(i, j) = oActiveSheet.Cells(i, j).Value
        Next
    Next
End With

Then assign oActiveSheet to the destination chart's worksheet (as seen at the top):
With oActiveSheet
   ' clear original data
   .Cells.Clear
    For i = 1 To rowCount
        For j = 1 To columnCount
            .Cells(i, j).Value = dataArray(i,j)
        Next
    Next
End With

One final note, since the data ranges may not exactly match in size, you'll need to run something like this to reset the data range after copying all of the data over:
oChart.SetSourceData "='Sheet1'!$1$1:$" & ColLetter(columnCount) & "$" & rowCount

Where the following function converts your max column from an integer to Excel alphanumeric columns:
Function Col_Letter(lngCol As Long) As String
    Dim vArr
    vArr = Split(Cells(1, lngCol).Address(True, False), "$")
    Col_Letter = vArr(0)
End Function

Again, this is a little convoluted, but the data labels are basically just text unconnected to the underlying data. So to affect the actual data, leave the data labels alone and get at the underlying worksheet.

A: To my knowledge, that backend Excel file driving an embedded PPT chart is not accessible using the VBA object model. There are extensive options for using VBA to affect the look and feel of the chart itself, but I've never found a way to assign the underlying Excel to a Worksheet object (or similar) and directly manipulate the values in the data sheet. Everything applied to the chart is superficial and "disconnected" from the sheet.
If the PPT chart is linked to data stored in an external Excel file, it's actually quite easy to get at that Excel file and manipulate the source data (I've written an addin that works this way to get around the problem). But for embedded charts, the data sheet is functionally invisible to VBA, as far as I can tell.


text:
Q: Xamarin iOS - How to debug a background service I am building an app that uses the location services which will start the app when it is in the terminated state using the startMonitoringSignificantLocationChanges.  I would like to attach the Xamarin Studio debugger to the process when it starts in the background but it doesn't seem possible in Xamarin Studios.  It is easy to attach the debugger and run the application, and even debug in the background, but when the app is terminated, so is the debugging session.  I can't find a way to attach the Xamarin Studios debugger to the process that starts when a location update is recieved
My question is the exact same at this, but I want to do that is Xamarin: How do I debug an iPhone app that's supposed to be launched by location services, into the background, from a terminated state?
Is there any good way to do this?
Thank you for the help


text:
Q: Searching Large String for file path. Return filepath + filename I've got a little project where I'm trying to download a series of wallpapers from a web page.  I'm new to python.
I'm using the urllib library, which is returning a long string of web page data which includes
<a href="http://website.com/wallpaper/filename.jpg">

I know that every filename I need to download has
'http://website.com/wallpaper/'

How can i search the page source for this portion of text, and return the rest of the image link, ending with "*.jpg" extension?
r'http://website.com/wallpaper/ xxxxxx .jpg'

I'm thinking if I could format a regular expression with the xxxx portion not being evaluated? Just check for the path, and the .jpg extension.  Then return the whole string once a match is found
Am I on the right track?

A: I think a very basic regex will do.
Like:
(http:\/\/website\.com\/wallpaper\/[\w\d_-]*?\.jpg)

and if you use $1this will return the whole String  .
And if you use
(http:\/\/website\.com\/wallpaper\/([\w\d_-]*?)\.jpg)

then $1 will give the whole string and $2 will give the file name only.
Note: escaping (\/) is  language dependent so use what is supported by python.

A: BeautifulSoup is pretty convenient for this sort of thing.
import re
import urllib3
from bs4 import BeautifulSoup

jpg_regex = re.compile('\.jpg$')
site_regex = re.compile('website\.com\/wallpaper\/')

pool = urllib3.PoolManager()
request = pool.request('GET', 'http://your_website.com/')
soup = BeautifulSoup(request)

jpg_list = list(soup.find_all(name='a', attrs={'href':jpg_regex}))
site_list = list(soup.find_all(name='a', attrs={'href':site_regex}))

result_list = map(lambda a: a.get('href'), jpg_list and site_list)

A: Don't use a regular expression against HTML.
Instead, use a HTML parsing library.
BeautifulSoup is a library for parsing HTML and urllib2 is a built-in module for fetching URLs
import urllib2
from bs4 import BeautifulSoup as bs

content = urllib2.urlopen('http://website.com/wallpaper/index.html').read()
html = bs(content)
links = [] # an empty list

for link in html.find_all('a'):
   href = link.get('href')
   if '/wallpaper/' in href:
      links.append(href)

A: Search for the "http://website.com/wallpaper/" substring in url and then check for ".jpg" in url, as shown below:
domain = "http://website.com/wallpaper/"
url = str("your URL")
format = ".jpg"
for domain in url and format in url:
    //do something


text:
Q: Magento 2.4.2 - issue with hide out of stock product I noticed issue with hide out of stock products. All visible on frontend.

*

*Reindex completed (all indexes sucess)

*indexes reset

*option hide  out of stock enabled correct

*c:f, s:up etc done.

*Qty:0 MSI: 0

Still visible on frontend. Any solution?


text:
Q: Speed comparison of two code I believe there are many similar questions, sorry if this is too common. I want to learn which one is better/faster/space efficient etc and why.
public static void(String[] main){
    //case 1
    String[] str_arr = new String[n];
    method1(str_arr)

    //case 2
    String[] str_arr = new String[n];
    String[] arr = new String[n];
    for(int i=0; i < n; i++){
        arr[i] = str_arr[i].split("some_char")[2];
    }
    method2(arr);
}

void method1(String[] str_arr){
    String[] arr = new String[n];
    for(int i=0; i < n; i++){
        arr[i] = str_arr[i].split("aChar")[2];//assume there are 50 of aChar
    }
//  do_something with arr ;
}

void method2(String[] arr){
//  do_something with arr ;
}

Which one should I prefer?
Thanks in advance.

A: This is purely up to your discretion.
When it comes to performance reasons:

*

*Use enhanced for loops, where you can, as they can sometimes impact the loop performance (see a nice micro-benchmark here: Java Enhanced-For-Loop FASTER than traditional?), or...

*Do not create additional storage array if you do not need the originals anymore. Simply read the value, split() it and store it back. On very large arrays, you'll save yourself some allocation time and space.

*In this particular example, the actual cost of method invocation is neglible. If you're extra paranoid (not recommended) you could make the method static to prevent being it thiscall function.

In terms of clean and tidy code:

*

*Your method looks like it may be something generic so it's a great candidate for just a method that takes an array, along with the delimiter, and splits all its elements.

*main() code is by convenience advised to be as small and compact as possible.

TL;DR Go for the first option, and eventually make some modification.
Also, it may be a good idea to split the elements before actually putting them inside the array.


text:
Q: uploadify upload There is a problem when I want to upload a picture, It does not upload pictures more than 3 MB, I located php.ini files and changed all the needed variables as needed, there is another ajax file upload script on my page right now, It works normal, uploads up to 40 MB, so the problem is not my php.ini for sure, are there any flash configurations that I should change ? and I placed fileSizeLimit 10 mb in my script, thank you :)
<?php $timestamp = time();?>
    $(function() {
        $('#file_upload').uploadify({
            'formData'     : {
                'timestamp' : '<?php echo $timestamp;?>',
                'token'     : '<?php echo md5('unique_salt' . $timestamp);?>'
            },
            'swf'      : 'uploadify.swf',
            'uploader' : 'uploadify.php',
            'sizeLimit'   : 10120*10120
        });
    });


text: Q: The Arrow in pop up menu has gone and icons in the menu bar on the top of the screen disappear after clicking Could anybody tells me how to solve this problem? It's very frustrating to see this from time to time in my laptop. I was trying to post a question on Apple Community, and I don't know why their website won't let me do so.


text:
Q: Java Gui label does not show up in the desired location on screen I have created a small GUI in Java Swing but I am facing a tiny issue with the location of the label.
I need to show the label at the top center of the frame but in my code even if I add set bounds, it still shows up in the wrong place. How do I display the label in the center?
The panel also does not get displayed on my screen. Not sure why.
My Code
public class GuiInterface {
    public void GUI()
    {

    // Frame
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("This");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Fonts
    Font  f2  = new Font(Font.SANS_SERIF,  Font.BOLD, 20);
    Font  f3  = new Font(Font.SANS_SERIF,  Font.PLAIN, 15);

    //Components

    JPanel mPanel=new JPanel();
    mPanel.setBackground(Color.lightGray);
    mPanel.setLayout(new BorderLayout());

    JButton jb1 = new JButton("Here");

    // Text Area
    JTextArea fTextArea=new JTextArea();
    //fTextArea.setBounds(60,150, 400,400);
    fTextArea.setMargin(new Insets(3,3,3,3));
    fTextArea.setEditable ( false ); // set textArea non-editable
    JScrollPane scroll = new JScrollPane(fTextArea);

    JLabel tittle= new JLabel("Fault");
    // tittle.setBounds(30,30, 400,20);
    tittle.setFont(f2);

    //Adding the components to the panel
    mPanel.add(jb1, BorderLayout.SOUTH);

    // Frame Settings
    frame.add(mPanel);
    frame.add(tittle);
    frame.pack();
    frame.setVisible(true);
    frame.setSize(800,800);

}
}

Updated Version of my code
Label appears along with the panel but the components added within the panel does not show up.
public class GuiInterface {
    public void GUI()
    {

    // Frame
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("Now");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());

    //Fonts
    Font  f2  = new Font(Font.SANS_SERIF,  Font.BOLD, 20);
    Font  f3  = new Font(Font.SANS_SERIF,  Font.PLAIN, 15);

    JPanel fPanel=new JPanel();
    fPanel.setBackground(Color.BLUE);
    fPanel.setLayout(new BorderLayout());

    JButton jb1 = new JButton("Here");

    // Text Area
    JTextArea fTextArea=new JTextArea();
    //fTextArea.setBounds(60,150, 400,400);
    fTextArea.setMargin(new Insets(3,3,3,3));
    fTextArea.setEditable ( false ); // set textArea non-editable
    JScrollPane scroll = new JScrollPane(fTextArea);

    JLabel tittle= new JLabel("Fault Localization",JLabel.CENTER);
    tittle.setFont(f2);

    //Adding the components to the panel
    fPanel.add(jb1, BorderLayout.NORTH);
    fPanel.add(fTextArea, BorderLayout.SOUTH);

    // Frame Settings
    frame.add(fPanel,BorderLayout.CENTER);
    frame.add(tittle,BorderLayout.NORTH);
    frame.setVisible(true);
    frame.setSize(800,800);

}
}

A: I don't know what the result should look like. But you don't assign a specific Layout to the JFrame and just add the Label to the JFrame.
The default Layout for JFrame is the BorderLayout. If you want a Component to appear at a specific position (for Example at the top), you have to specify the area. The BorderLayout got 5 different areas: NORTH, EAST, SOUTH, WEST and CENTER.
So what you should probably do is JFrame.add(JLabel, BorderLayout.NORTH) to assign you label at the top of the JFrame.
By the way, you should not use both JFrame.pack and JFrame.setSize(), and JFrame.setVisible() should always be your last method call. In your example it makes no difference, but it would, if you decided to add Components after the method call.

A: in you first code :
you must add this 2 line after declaration tittle :
    tittle.setHorizontalAlignment(SwingConstants.CENTER);
    tittle.setVerticalAlignment(SwingConstants.TOP);

in update version
It depends on how you want to use this class.
One way to use it can be like this :
    GuiInterface gi = new GuiInterface();
    gi.GUI();

and result is :


text:
Q: Camel, parameterized query and converter I'm newbie in Camel, I would like to known if it's possible to convert a Camel header message value before to pass it to a parameterized query ? I use Camel and Spring boot.
In below example, I would like the object "o" to be converted automatically into string, for example, and injected into the query.
from("direct:test").setHeader("y", o).to("sql:select * from x where a = :#y")
It's possible ? Thanks

A: from("direct:test").setHeader("y", o).to("bean:someBean?method=somePublicMethod").to("sql:select * from x where a = ${body}")

Write a bean class  with id someBean or just name the class as SomeBean and inside that write a public method called somePublicMethod. Inside that you can convert and set the result to camel message body.  Something like this
public void handleFiegeReadyEvent(Exchange exchange){
    exchange.getIn().getBody(); // retrieve the body of the message from previous stage. Cat it ti appropriate type.
    // do whatever you want to do here and generate the result
    exchange.getIn().setBody(result);
    exchange.getIn().setHeader("key1", value1);
    exchange.getIn().setHeader("key2", value2);
}


text:
Q: Accessing Data from Python Pandas The below is a pandas basic assignment question.

Create a series named heights_A with values 176.2, 158.4, 167.6,
156.2, and 161.4. These values represent heights of 5 students of class A.
Label each student as s1, s2, s3, s4, and s5.
Create another series named weights_A with values 85.1, 90.2, 76.8,
80.4, and 78.9. These values represent weights of 5 students of class A.
Label each student as s1, s2, s3, s4, and s5.
Create a dataframe named df_A, which holds the height and weight of
five students s1, s2, s3, s4 and s5.
Label the columns as Student_height and Student_weight, respectively.
Select the column df_A referring to student heights, and store it in
the variable height. Note: Specify the required column name inside
square brackets.
Print the type of object of the variable height.

Tried with the below code till now, but the checker seems to think height data type is not correct.
Not sure where is this being incorrect.
import pandas as pd
import numpy as np

heights_A =  pd.Series([176.2, 158.4, 167.6, 156.2, 161.4])

heights_A.index = ['s1', 's2', 's3', 's4','s5']

weights_A = pd.Series([85.1, 90.2, 76.8, 80.4 , 78.9])

weights_A.index = ['s1', 's2', 's3', 's4','s5']

df_A = pd.DataFrame()

df_A['Student_height'] = heights_A

df_A['Student_weight'] = weights_A

height = df_A[['Student_height']]
height.dtypes

Not sure what is incorrect with this height datatype part

A: Just try:
height = df_A['Student_height']
#height.dtypes #dont use this as they are asking for the type of object
print(type(height))

type() function will give you the type of the height object. If you try with object.dtype it will give the datatype.
When you were using double square brackets the heights variable is a df, when you just use single square brackets a series is returned. Seems like your question wants a series returned.


text:
Q: In My Vscode i m using menlo font but the brackets "<", ">" are pixel cracking and texts are also has poor quality is there any way to fix? [enter image description here][1]
I wanted to fix the poor quality of the font
[1]: https://i.stack.imgur.com/qNWK8.png


text:
Q: How best to enable end-user configuration of wifi or Ethernet on embedded device? I'm building a device that includes an embedded Linux computer and I need to allow the device user to (easily) configure the device to connect to their wired or wireless network.
I know there are technologies on the horizon which might make this easier, such as ProbMe, but I need a solution I can implement now using standard wifi equipment.
As I've seen done for some wireless equipment, an embedded web server could allow the user to start with a wired connection, connect to an embedded web server, and setup their wifi that way.  Is there a commodity such web server app, or is this something everyone rolls their own of?
Even with an embedded web server, establishing a wired connection to said server is potentially beyond the skills of basic users as they'd have to change the host computer's static IP address and navigate their browser to an IP-based address.  Again, does anyone know of something off-the-shelf for this sort of thing, or is this just something developers handle anew for each product?
This seems like an increasingly common problem as we move towards the IoT, so hopefully there are reusable components to be had here.  I've searched around somewhat, but it's actually a little tricky to search for something as odd as a web server to configure an embedded internet client.  Anyone know of anything?

A: I still haven't found anything in terms of a configuration web server as stated in my question, but this article addresses the general problem really well and lays out the current options.  Essentially options include:

*

*Wi-Fi protected setup including

*

*USB flash drive configured from an AP (rare)

*PIN

*Push button (possibly the best solution when there is access to the AP)

*NFC

*Access Point (AP) mode - device initially acts as an AP; connected to and configured (very attractive for initial setup but could be problematic for changes - maybe add a button that resets the device back into AP mode, or have it auto-revert when it can't successfully communicate)

*Ad-hoc mode

*Vendor specific solutions

*Bluetooth - setup device's Wi-Fi through a mobile app

Of these, only AP Mode seems to me like a full-proof method that could work in home, business, and industrial settings.  It could even offer the feature that connected clients would be auto-redirected to the configuration page, like public Wi-Fi services often do.  It would be great if someone developed an open source such a solution for the major OSes.  Anyone know of anything?


text:
Q: java, regular expression, need to escape backslash in regex With reference to below question -
String.replaceAll single backslashes with double backslashes
I wrote a test program, and I found that the result is true in both cases, whether I escape the backslash or not.  This may be because
- \t is a recognized Java String escape sequence. (Try \s and it would complain).
- \t is taken as literal tab in the regex.
I am somewhat unsure of the reasons.
Is there any general guideline about escaping regex in Java.  I think using two backslashes is the correct approach.
I would still like to know your opinions.
public class TestDeleteMe {

  public static void main(String args[]) {
    System.out.println(System.currentTimeMillis());

    String str1 = "a    b"; //tab between a and b

    //pattern - a and b with any number of spaces or tabs between
    System.out.println("matches = " + str1.matches("^a[ \\t]*b$"));
    System.out.println("matches = " + str1.matches("^a[ \t]*b$"));
  }
}

A: There are two interpretations of escape sequences going on: first by the Java compiler, and then by the regexp engine. When Java compiler sees two slashes, it replaces them with a single slash. When there is t following a slash, Java replaces it with a tab; when there is a t following a double-slash, Java leaves it alone. However, because two slashes have been replaced by a single slash, regexp engine sees \t, and interprets it as a tab.
I think that it is cleaner to let the regexp interpret \t as a tab (i.e. write "\\t" in Java) because it lets you see the expression in its intended form during debugging, logging, etc. If you convert Pattern with \t to string, you will see a tab character in the middle of your regular expression, and may confuse it for other whitespace. Patterns with \\t do not have this problem: they will show you a \t with a single slash, telling you exactly the kind of whitespace that they match.

A: Yes, there is a general guideline about escaping: Escape sequences in your Java source get replaced by the Java compiler (or some preprocessor eventually). The compiler will complain about any escape sequences it does not know, e.g. \s. When you write a String literal for a RegEx pattern, the compiler will process this literal as usual and replace all escape sequences with the according character. Then, when the program is executed, the Pattern class compiles the input String, that is, it will evaluate escape sequences another time. The Pattern class knows \s as a character class and will therefore be able to compile a pattern containing this class. However, you need to escape \s from the Java compiler which does not know this escape sequence. To do so, you escape the backslash resulting in \\s.
In short, you always need to escape character classes for RegEx patterns twice. If you want to match a backslash, the correct pattern is \\\\ because the Java compiler will make it \\ which the Pattern compiler will recognize as the escaped backslash character.

A: The first form \\t will be expanded to a tab char by the pattern class.
The second form \t will be expanded to a tab char by Java before it builds a pattern.
In the end, you get a tab char either way.

A: With org.apache.commons.lang3.StringEscapeUtils.unescapeJava(...), you can escape most of the common spl.chars and also the unicode characters (converts unicode charset to readable regular character)


text:
Q: timedate reformatting My Python script is currently writing out my date from the timedate module request as follows:
2019-08-28 14:56:52.559047
I want it to be converted to:
Aug 28

A: You can use the datetime module.
>>> import datetime
>>> now = datetime.datetime.now()
>>> now.strftime("%b %d")
'Aug 28'

I'd suggest reading about the datetime module (official docs) and strftime.
Relevant SO question: How to print a date in a regular format?


text:
Q: Deleted everything from iCloud but storage space not freed I have deleted everything from my iCloud account storage but it still has 2.4 GB storage available and I can not free all the space.

A: It looks like iCloud Drive is still on:
Delete all files from it and then turn it off.

A: Im guessing you have looked in iCloud drive that are still enabled what kind of files and stuff are stored there from your phone.
If its not easily managed in your phone you can try accessing icloud.com in a browser and go to iCloud drive, perhaps you have some files there you can delete to recover some storage.


text:
Q: Angular 12/rxjs 7/angularfire: async token interceptor with deprecated toPromise I am using angularfire with and auth interceptor adding a token to every request. This interceptor requires an async call as the token might requires a refresh.
With an update to rxjs 7, my async tokenHandler now faces two issues:

*

*the .toPromise() is depcrated

*the async tokenHandler may returns undefined (Type 'HttpEvent | undefined' is not assignable to type 'HttpEvent')

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(private auth: AuthService) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const fireUser = this.auth.fireAuthUser.value;

    if (fireUser) {
      // convert promise to observable using 'from' operator
      return from(this.tokenHandler(request, next, fireUser));
    }

    return next.handle(request);
  }

  async tokenHandler(request: HttpRequest<any>, next: HttpHandler, currentUser: firebase.User): Promise<HttpEvent<any>> {
    const authToken = await currentUser.getIdToken().then();

    if (authToken) {
      request = request.clone({ setHeaders: { Authorization: 'Bearer ' + authToken } });
    }

    return next.handle(request).toPromise();
  }
}

Could you advise me on how to rewrite the async tokenHandler?

A: stream$.toPromise() is most semantically similar to the new lastValueFrom(stream$) except:
The type information of toPromise was wrong.
When the source Observable completed without ever emitting a single value - it resolved with undefined. It should reject in that case, but it doesn't. lastValueFrom and firstValueFrom will both reject in this case.
Therefore, you can fix this with lastValueFrom or firstValueFrom.
async tokenHandler(
  request: HttpRequest<any>,
  next: HttpHandler,
  currentUser: firebase.User
): Promise<HttpEvent<any>> {
  const authToken = await currentUser.getIdToken();

  if (authToken) {
    request = request.clone({ setHeaders: { Authorization: 'Bearer ' + authToken } });
  }

  return lastValueFrom(next.handle(request));
}


text:
Q: SFML - Move object towards coord so I am working on an AI system with C++ and SFML in which I want the enemies to follow the player. Im going to create it so the enemies are moving towards the point at which the player was 30 frames ago (so it will constantly updating). But my question is simple, what is the math behind getting the enemy to move to a specific point? Like let's say the player is at (230, 400) and the enemy is at (100, 200) how do I get the enemy (using the .move() function with a speed of 3) to move to that point? Any help would be fantastic!
---UPDATED BELOW WITH CURRENT CODE FOR HANDLING MOVEMENT-----
float angle = atan2(v2iEnemyPos[1].y - rsPlayer.getPosition().y, v2iEnemyPos[1].x - rsPlayer.getPosition().x);
    angle =angle * 180 / (atan(1) * 4);
   sf::Vector2f newpos((cos(angle))*2, (sin(angle))*2);
    std::cout << newpos.x << " " << newpos.y << std::endl;
    rsEnemy[1].move(newpos.x, newpos.y);
    rwWinOne.draw(rsPlayer);
    rwWinOne.display();
    rwWinOne.clear();

A: The direction to move your enemy into is simply the difference between the player position and the enemy position. However, you want the enemies to move with constant speed, so you need to normalize the result. This will give you the direction as a vector of length 1.
Vector2u direction = normalize(player.getPosition() - enemy.getPosition());

You can now multiply this direction by the speed constant of that enemy's type. The result is a vector with it's length depending on the speed factor instead of the distance to the player. Just use the result to move your enemy.
enemy.move(speed * direction);

However, you perform that once a frame and framerates can vary between machines and configurations. Therefore, you should add a the elapsed time since the last move call, which might be your frame time, as factor to the equation. This way, if a frame takes a longer than usual, the enemy will be moved further to comprehend this, and vice versa.
// Initialize a timer
sf::Clock clock;

// Get elapsed time at the beginning of a frame
// I multiply this by target framerate to get a value around one
float delta = clock.restart().asSeconds() * 60;

// Move all objects based on elapsed time
Vector2u direction = normalize(player.getPosition() - enemy.getPosition());
enemy.move(delta * speed * direction);

By the way, basic knowledge of linear algebra is needed very often in game development, so you might pay out to attend an online course.

A: You should consider the elapsed time (since last frame) - dt - in your calculation.
The enemy has a given speed: enemy_velocity.
I won't use the move() function, but the SetPosition().
You have to calculate the new position of the enemy:
enemy.x += dt * enemy_velocity * cos(angle);
enemy.y += dt * enemy_velocity * sin(angle);

And affect it with SetPosition().


text:
Q: Limit over exponential I am trying to solve few questions though I know there answers I am not able to figure out the solution. I have tried to apply L'Hopital Rule as well as e^(ln) way for solving it but I am not obtaining desired answers. Your help will be much appreciated. Thank you. Here are the questions with their answers
1- $\lim_{x\to\inf}(1-\frac{4}{x-1})^{3x-1}$$=e^{-12}$
2-$\lim_{x\to2}\frac{2^x-x^2}{x^x-2^2}=\frac{log2-1}{log2+1}$

A: The first one is a very standard limit. Note that $(1-\frac{4}{x-1})^{3x-1}=((1-\frac{1}{\frac{x-1}{4}})^{\frac{x-1}{4}})^{(3x-1)\frac{4}{x-1}}$. Can you finish from here?
For the second one just use L'Hopital rule once. To differentiate $x^x$ write it in the form $x^x=e^{xlnx}$.

A: *

*$(1-\frac{4}{x-1})^{3x-1}=(1-\frac{4}{x-1})^{3x-3}(1-\frac{4}{x-1})^{2}=((1-\frac{4}{x-1})^{x-1})^3(1-\frac{4}{x-1})^{2 }\to (e^{-4})^3 \cdot 1 = e^{-12}$ as $x \to \infty.$

*What are your problems with  L'Hopital's Rule ? This rule works for $ \lim_{x\to2}\frac{2^x-x^2}{x^x-2^2}$ !

A: $$\lim_{x\to2}\dfrac{2^x-x^2}{x^x-2^2}=\lim_{x\to2}\dfrac{2^x-2^2-(x^2-2^2)}{x^x-x^2+x^2-2^2}=\dfrac{2^2\cdot\lim_{x\to2}\dfrac{2^{x-2}-1}{x-2}-\lim_{x\to2}\dfrac{x^2-2^2}{x-2}}{x^2\cdot\lim_{x\to2}\dfrac{x^{x-2}-1}{x-2}+\lim_{x\to2}\dfrac{x^2-2^2}{x-2}}$$
$$=\dfrac{4\ln2-(2+2)}{4\ln2+(2+2)}$$
$$\lim_{x\to2}\dfrac{x^{x-2}-1}{x-2}=\dfrac{d(x^x)}{dx}_{\text{ at } x=2}$$

A: Use that
$$\left(1-\frac{4}{x-1}\right)^{3x-1}=\left[\left(1-\frac{4}{x-1}\right)^{\frac{x-1}{4}}\right]^{\frac{4(3x-1)}{z-1}}$$
and by $x=2+t, \quad t \to 0$
$$\frac{2^x-x^2}{x^x-2^2}=\frac{2^{t+2}-(t+2)^2}{(t+2)^{t+2}-2^2}=\frac{4\cdot 2^{t}-4+4-(t+2)^2}{(t+2)^{t+2}-4}=$$
$$=\left(4\cdot\frac{ 2^{t}-1}{t}+\frac{4-(t+2)^2}{t}\right)\frac{t}{(t+2)^{t+2}-4}\to\frac{4\log 2-4}{4\log 2+4}=\frac{\log 2-1}{\log 2+1}$$
indeed
$$\frac{(t+2)^{t+2}-4}{t}=\frac{e^{(t+2)\log(t+2)}-4}{t}=\frac{e^{2\log(t+2)}\cdot e^{t\log(t+2)}-e^{2\log(t+2)}+e^{2\log(t+2)}-4}{t}=$$
$$=(t+2)^2\frac{e^{t\log(t+2)}-1}{t\log(t+2)}\frac{t\log(t+2)}{t}+\frac{(t+2)^2-4}{t} \to4\log 2+4$$


text:
Q: Format the datetime to get date and hour information How to get the date and hour information for a given datetime object in Transact-SQL?
E.g. 2014-12-18 21:00:00 for 2014-12-18 21:24:05.
I need to truncate off all parts after the hour - i.e. minutes, seconds, and partial seconds.

A: For SQL Server:
Select DATEPART(HOUR, [date]) + ":" + DATEPART(MINUTE, [date]);

Oracle:
Select TO_CHAR([date], 'HH:MI') From...

A: SELECT
CONVERT(TIME,GETDATE()) AS TimeOnly,
CONVERT(DATE,GETDATE(),101) AS DateOnly
GO

Replace the GETDATE() function with whatever you need.


text:
Q: Complete password field scp command on linux Im writing a shell script to use the scp command (ssh) to transfer a file across to a computer. This obviously is password protected is there a way on either end to either...disable the password or to auto complete the password for the customer?
This out of pure convience and I have no idea if it is possible (im fairly new to linux), any help or pointers would be appreciated.
Thanks in advance

A: You can generate a pair of RSA/DSA keys (public and private). In your terminal:
$ ssh-keygen

It will generate a pair of files:

*

*Private key: .ssh/id_dsa

*Public key: .ssh/id_dsa.pub
Then, if you have access to remote host, you can add your public key to .ssh/authorized_keys file. In your remote host, copy the public key and use the following command:
cat id_dsa.pub >> .ssh/authorized_keys

A: You should you public key identification if you have access to SSH keys on both machines.

A: have a look at ssh keys. github has a nice intro


text:
Q: Delete from row to row in phpadmin I have a table with many rows and I want want to delete from row to row but I do know the right comand.
I know that code for deleting just single row:
DELETE FROM `ps_econt_order` WHERE `ps_econt_order`.`econt_order_id` = 108500;

Also that I am using that code:
DELETE FROM `ps_econt_order` WHERE `ps_econt_order` IN (500,501,504,503);

BUT I would want to delete all rows from 505 to 108500 just with single command.

A: if the rows are in ordered sequence you could use between
DELETE FROM ps_econt_order
WHERE econt_order_id between 500 and 108500


text:
Q: How to convert average horse power? My question is

" A locomotive engine draws a load $m$ pounds up an inclined plane making angle  $a$   with horizontal, the coefficient of friction being  $k$ . If  starting from rest and moving with uniform acceleration,  it acquired a velocity of $v$ ft/sec in $t$ seconds , find the average Horse Power at which the engine has worked  ".

In the question   author calculate Average velocity
=( v+0)/2  . Then he calculate  Avereg H.P ( horse power) =
P×V/2g where P be the force   applied by the engine along the plane to pull the partical  . He resolved  mgsina + kR   along the plane  where R   is the normal reaction  and make equation of motion     mf = P-mgsina -kR. My problem is  in the calculation of  Average H.P why he divide it  by g .
Also he use vertically downward  force  as mg  . I want to ask if m is in pound then what is unit of mg ?
Please help me . This subject is not of my field . Only because it seems most interesting to me that is why I learn it . Please help


text:
Q: uialertview clickedButtonAtIndex message sent to deallocated instance I created a UIAlertView that is in ViewDidLoad, as the following:
    prompt = [[UIAlertView alloc] init];
    prompt.title = @"تسجيل الدخول";
    prompt.message = @"\n\n\n";
    prompt.delegate = self;
    [prompt addButtonWithTitle:@"الغاء"];
    [prompt addButtonWithTitle:@"دخول"];

    userNameTxtField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 50.0, 260.0, 25.0)];
    [userNameTxtField setBackgroundColor:[UIColor whiteColor]];
    [userNameTxtField setPlaceholder:@"اسم المستخدم"];
    [prompt addSubview:userNameTxtField];

    passwordTxtField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 85.0, 260.0, 25.0)];
    [passwordTxtField setBackgroundColor:[UIColor whiteColor]];
    [passwordTxtField setPlaceholder:@"كلمة المرور"];
    [passwordTxtField setSecureTextEntry:YES];
    [prompt addSubview:passwordTxtField];

    [prompt show];
    //[prompt release];

    // set cursor and show keyboard
    [userNameTxtField becomeFirstResponder];

and the clickedButtonAtIndex function is as following:
 -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex ==0) {
    NSLog(@"cancel");
}else {
    NSLog(@"will login isA");
}
}

but when I click any buttons, I see the output and then the app crashes and gives me the following Exception:
   [MaktabatyTableViewController respondsToSelector:]: message sent to deallocated instance 0x894cfa0

Any help ????

A: i have tried your code. your code working nicely .
-(void)viewDidLoad
{

    UIAlertView *prompt = [[UIAlertView alloc] init];
    prompt.title = @"تسجيل الدخول";
    prompt.message = @"\n\n\n";
    prompt.delegate = self;
    [prompt addButtonWithTitle:@"الغاء"];
    [prompt addButtonWithTitle:@"دخول"];

    UITextField *userNameTxtField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 50.0, 260.0, 25.0)];
    [userNameTxtField setBackgroundColor:[UIColor whiteColor]];
    [userNameTxtField setPlaceholder:@"اسم المستخدم"];
    [prompt addSubview:userNameTxtField];

    UITextField *passwordTxtField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 85.0, 260.0, 25.0)];
    [passwordTxtField setBackgroundColor:[UIColor whiteColor]];
    [passwordTxtField setPlaceholder:@"كلمة المرور"];
    [passwordTxtField setSecureTextEntry:YES];
    [prompt addSubview:passwordTxtField];

    [prompt show];
    //[prompt release];

    // set cursor and show keyboard
    [userNameTxtField becomeFirstResponder];
}


text:
Q: Can't Set Up IPv4 Server I've been experimenting with sockets lately. I tried to make a simple program where a client could connect to me (host) and any text that they would enter would be sent to me. I tried to run my program on my IPv4 because I wanted to share this program with my friends that are on different PC's. Here is the host code:
import socket

s = socket.socket()

print "Server socket created."

s.bind(('my actual IPv4 address here',9999))

s.listen(3)
print "Waiting for connections."

while True:
    c, addr = s.accept()
    name = c.recv(1024)
    print name, " Connected with ", addr
    c.send(bytes('Connected to the server.'))
    while True:
        usertxt = c.recv(1024)
        print name, " said ", usertxt
        c.send(bytes(usertxt))
        if usertxt == "close":
            c.close()
        else:
            continue

The error that I get is "The requested address is not valid in its context" on line 7
Thanks.


text:
Q: How to make CodeIgniter file upload class accept all extensions? Currently if I supply no extensions to the class it allows no extensions. I would like to allow all extensions. Is there any way to do this without hacking the core?

A: In Codeigniter 2, you simply need to define allowed types like this :
$config['allowed_types'] = '*';

A: The answer to your direct question: No, there's no way to do this without overriding the core
To good news is you can avoid hacking the core, per the manual

As an added bonus, CodeIgniter permits your libraries to extend
  native classes if you simply need to add some functionality to
  an existing library. Or you can even replace native libraries just
  by placing identically named versions in your application/libraries folder.

So, to have a drop in replacement for your library, you could copy Upload.php to your
application/libraries

folder, and then add your custom logic to that Upload.php file.  Code Igniter will include this file instead whenever you load the upload library.
Alternately, you could create your OWN custom uploader class that extends the original, and only refines the is_allowed_filetype function.
application/libraries/MY_Upload.php
class MY_Upload Extends CI_Upload{
    function is_allowed_filetype(){
         //my custom code here
    }
}

You'll want to read over the changelog whenever you're upgrading, but this will allow you to keep your code and the core code in separate universes.

A: What I do is:
$ext=preg_replace("/.*\.([^.]+)$/","\\1", $_FILES['userfile']['name']);
$fileType=$_FILES['userfile']['type'];
$config['allowed_types'] = $ext.'|'.$fileType;

That makes all files in every function call automatically allowed.

A: So far it looks like it would only be possible via a hack.
I inserted a return true on line 556 in system/libraries/Upload.php.

A: $config['allowed_types'] = '*';
 Which Will Upload Any File Formats Like .exe or .jpegs extra...

A: if all not works then rearrange the allowed type order like that in first video format
$config['allowed_types'] = 'mp4|jpg|png|'

It will works in my case so I shared if possible try it.

A: You simply need to replace this condition:
        if (! $this->is_allowed_filetype())
        {
            $this->set_error('upload_invalid_filetype');
            return false;
        }

With:
        if (count($this->allowed_types) && !$this->is_allowed_filetype())
        {
            $this->set_error('upload_invalid_filetype');
            return false;
        }

A: $config['allowed_types'] = '*'; is possible solution, but IMHO it is not very safe. The better way is to add a file types you need to $config['allowed_types']. In case the CodeIgniter doesn't have the MIME types you need, you can add them by editing file mimes.php in "application/config" folder. Just include your mime types in array.
Example of adding epub and fb2 file types:
return array(
'epub'  =>  'application/epub+zip',
'fb2'   =>  'application/x-fictionbook+xml',
'hqx'   =>  array('application/mac-binhex40', 'application/mac-binhex', 'application/x-binhex40', 'application/x-mac-binhex40'),

Then you'll be able to use the extensions you added in $config['allowed_types'] variable.


text:
Q: Cannot change Log level using Log4j2 Below is my code to change the logging level in Log4j2. I got this from one other stackoverflow thread.
It used to work earlier when I didn't have the Log4j2.xml configurator, but for some reason this has stopped working for me after I started using the configurator .
The log level does not change at runtime anymore.
public MyLogger() {
    Logger log = LogManager.getLogger(MyLogger.class.getName());
}

public void setLevel(Level level) {
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration conf = ctx.getConfiguration();
    LoggerConfig config = conf.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
    config.setLevel(level);
    ctx.updateLoggers(conf);
}

Here is my Lo4j2.xml configuration file. I got this also too online.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="ERROR">
   <Properties>
    <Property name="fileName">log/app.log</Property>
    <Property name="fileNamePattern">log/app.log-%d{dd-MM-yyyy}-%i.log</Property>
    <Property name="logPattern">%d{dd-MM-yyyy HH:mm:ss,SSS} [%t] %-5p %c{2} - %m%n</Property>
</Properties>
<Appenders>
    <Console name="Console" target="SYSTEM_OUT">
        <PatternLayout pattern="${logPattern}"/>
    </Console>
    <RollingFile name="MyRollingFile" fileName="${fileName}" filePattern="${fileNamePattern}">
        <PatternLayout pattern="${logPattern}"/>
        <Policies>
            <TimeBasedTriggeringPolicy/>
            <SizeBasedTriggeringPolicy size="20MB"/>
        </Policies>
        <DefaultRolloverStrategy max="10"/>
    </RollingFile>
</Appenders>
<Loggers>
    <Logger name="com.cf.re" level="error" additivity="false">
        <AppenderRef ref="Console"/>
        <AppenderRef ref="MyRollingFile"/>
    </Logger>
    <Root level="error">
        <AppenderRef ref="Console"/>
    </Root>
</Loggers>
</Configuration>

Can someone please point out the issue here? Or tell me how I can debug this issue?

A: What is the fully qualified class name of MyLogger? Does the package name start with "com.cf.re"?
You have 2 Loggers configured, root and "com.cf.re". You are only changing the log level of the root logger. If the package of MyLogger starts with "com.cf.re" and you also want to change that Logger's log level, then use this code:
public void setLevel(Level level) {
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration conf = ctx.getConfiguration();
    LoggerConfig root = conf.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
    root.setLevel(level);
    LoggerConfig named = conf.getLoggerConfig("com.cf.re");
    named.setLevel(level);
    ctx.updateLoggers(conf);
}

A: There is an easier way to do it and it is right there on the FAQ page in log4j2's site
https://logging.apache.org/log4j/2.x/faq.html#reconfig_level_from_code
Sample Code below:
Configurator.setLevel(logger.getName(), Level.INFO);


text:
Q: How to make UILabel fits its blue frame Is there any way to change padding/margin of UILabel in interface builder in Xcode 8?

I'd like to change the blue frame, so it fits "13" without this top/bottom padding.
I need it to set my contraints without any "magic" numbers to make "distance" label touch "13"
EDIT:

A: What i would do, is set the label height equal to the view height, judging from your screenshots should be ~0.3 .


text:
Q: Sun God vs. Temple of the Sun God? Which is better: 5 sun gods or 1 temple of the sun god? I don't want to sacrifice all my sun gods if the temple doesn't do better!

A: I believe (from personal experience) that the 5 sun gods are a lot stronger than a Temple of the sun god. Just keep it as is, it is plenty strong enough to handle many situations, if you have them strategically placed. Just keep buying sun gods.

A: Sun gods are more powerful not temple-ized. However, when you make a Temple of the Monkey God, all the other towers in its range are taken in and combined into the temple to make it have more power, plus now you have more space to build other towers, or more Temples if you like.
It is your choice, though, depending on your playing style.

A: The temple will do more damage to MOAB class bloons, so its better late game, where you can get it (unless youre like me and use tons of special agents and banana farms. The earliest ive gotten a perfect temple is round 60)

A: If you fully upgrade the monkey temple, then it is leagues above the sungods. However, if you don't sacrifice to the temple, the sun god is better in every respect.  To get a fully upgraded temple, if I remember right, you need 30k in each category: bombs(bomb and mortar), magic, ice, glue, and misc.  Also, you can sacrifice a monkey village to the monkey temple to give it the buffs internally. This doesn't stack with any other village you might or might not have on the temple itself after you upgrade it.


text:
Q: Replicating Kolmogorov's Counterexample for Fourier Series in Context of Fourier Transforms It is a famous result of Kolmogorov that there exists a (Lebesgue) integrable function on the torus such that the partial sums of Fourier series of $f$ diverge almost everywhere (a.e.). More specifically, he exhibited an $f\in L^{1}(\mathbb{T})$ such that
\begin{align*}
\sup_{N\geq 1}\left|S_{N}f(x)\right|=\sup_{N\geq 1}\left|(f\ast D_{N})(x)\right|=\infty, \qquad\forall \text{ a.e. } x\in\mathbb{T},
\end{align*}
where $S_{N}$ is the $N^{th}$ partial sum and $D_{N}$ is the $N^{th}$ Dirichlet kernel given below.
\begin{align*}
S_{N}f(x):=\sum_{\left|n\right|\leq N}\widehat{f}(n)e^{2\pi inx}, \quad D_{N}(x):=\dfrac{\sin 2\pi(N+\frac{1}{2})x}{\sin \pi x}
\end{align*}
and we identify $\mathbb{T}$ with the unit interval $[0,1]$.
I have read, for example pg. 118 in [Pinsky], that Kolmogorov's counterexample can be replicated in the context of the Fourier transform on the real line $\mathbb{R}$, showing that $L^{1}$ pointwise Fourier inversion can fail quite horribly. If my understanding is correct, then the following claim is true:

Claim. There exists a function $f\in L^{1}(\mathbb{R})$ such that
  \begin{align*} S_{R}f(x):=\int_{\left|\xi\right|\leq R}\widehat{f}(\xi)e^{2\pi i\xi x}\mathrm{d}\xi=\int_{\mathbb{R}}f(y)\dfrac{\sin 2\pi R(x-y)}{\pi (x-y)}\mathrm{d}y\not\rightarrow f(x), \qquad\forall\text{ a.e. }x\in\mathbb{R} \end{align*} as $R\rightarrow\infty$.

I have not seen a proof of this claim in the literature. Is there a way to directly take Kolmogorov's counterexample for the Fourier series and turn it into a counterexample for the Fourier transform? Or does one have to go back to the original proof and make the appropriate changes for the different setting? I haven't tried the latter yet, but my efforts at quicker, "details under the rug" approach have so far been unsuccessful.
I believe that it follows from the weak type (1,1) bound for the Hilbert transform that the partial sums of the Fourier integrals converge in measure to $f\in L^{1}(\mathbb{R})$ as $R\rightarrow\infty$. Whence, there exists a subsequence $\left\{R_{k}\right\}$ tending to $\infty$ such that $S_{R_{k}}f(x)\rightarrow f(x)$ a.e., as $R\rightarrow\infty$. So it cannot be true that
\begin{align*}
\lim_{R\rightarrow\infty}\left|S_{R}f(x)\right|=\infty, \qquad\forall \text{ a.e. }x\in\mathbb{R}
\end{align*}
But I don't see how this observation helps me in my original task.
[Kolmogorov] A.N. Kolmogorov, "Une série de Fourier-Lebesgue divergente presque partout," Fundamenta mathematicae 4.1 (1923), 324-328.
[Pinsky] M.A. Pinsky, An Introduction to Fourier analysis and Wavelets, Pacific Grove: Brooks/Cole, 2002.

A: Ok. Note that $2\pi=1$ here...
Say $f$ is Kolomogorov's example. Regard $f$ as a periodic function defined on the entire line. Let $c_n$ be the $n$-th Fourier coefficient of $f$ (we want to reserve \hat for the Fourier transform).
Say $\psi\ne 0$ is a smooth function with support in $(-1/2,1/2)$. Say $\psi$ is even just so we don't have to worry about the FT versus the inverse FT. There is a Schwarz function $\phi$ with $\psi=\hat\phi$.
Now define $g$ by $g(n+t)=c_n\psi(t)$ for $n\in\mathbb Z$ and $|t|<1/2$, $g(\xi)=0$ for other $\xi$.
Note that $f\phi\in L^1(\mathbb R)$; this is going to be the bad $L^1$ function. You can show without too much trouble that in fact $$g=\widehat{f\phi}.$$
Now consider $\int_{-(N+1/2)}^{N+1/2}g(\xi)e^{ix\xi}\,d\xi$. If we show that this is unbounded (as $N\to\infty$) for almost every $x$ we're done. But
$$\int_{-(N+1/2)}^{N+1/2}g(\xi)e^{ix\xi}\,d\xi=\sum_{-N}^Nc_n\int_{-1/2}^{1/2}\psi(t)e^{ix(n+t)}\,dt=C(x)\sum_{-N}^Nc_ne^{ixn}=C(x)S_N(x),$$which is unbounded at any point where $S_N$ is unbounded and $C(x)\ne0$. Here $C(x)=\int_{-1/2}^{1/2}\psi(t)e^{ixt}=\phi(x)$; hence $C(x)=0$ on at most a countable set, since $\phi$ is the restriction to $\mathbb R$ of an entire function. QED

Detail: Why is $\widehat{f\phi}=g$? Seems clear, took me a minute to give an actual proof.
Let $\epsilon>0$. Choose a trigonometric polynomial $p$ with $\int_0^1|f-p|<\epsilon$. Then $\|p\phi-f\phi\|_1<c\epsilon$, so
$$\|\widehat{f\phi}-\widehat{p\phi}\|_\infty<c\epsilon.$$
Now say $p(x)=\sum_{-\infty}^\infty a_ne^{int}$, where all but finitely many $a_n$ vanish. Then $|a_n-c_n|<\epsilon$ for all $n$. This shows that $$\|g-\sum_na_n\tau_n\hat\phi\|_\infty<c\epsilon,$$where $\tau_n$ denotes translation by $n$. Since $p$ is really a finite sum, $$\widehat{p\phi}=\sum_na_n\tau_n\hat\phi.$$So $\|g-\widehat{f\phi}\|_\infty<c\epsilon$.

A: This answer is intended to complement David's very nice solution by showing that the partial sums of the Fourier integrals are at most be pointwise unbounded almost everywhere (a.e.), when $f\in L^{1}(\mathbb{R})$; there exists a subsequence which converges to $t$ pointwise a.e. Combining this with David's solution, we see that the partial sums of the Fourier series are at most be pointwise unbounded a.e. This resolves an error I made in the original question by incorrectly claiming that Kolmogorov showed there exists an $f\in L^{1}(\mathbb{R})$ such that $\left|S_{N}f\right|\rightarrow\infty$ a.e.
The proof is a consequence of the weak type (1,1) boundedness of the Hilbert transform.

Lemma 1. The operators $S_{R}$ defined above are bounded $L^{1}(\mathbb{R})\rightarrow L^{1,\infty}(\mathbb{R})$, uniformly in $R>0$.

Proof. One can verify that for $f\in\mathcal{S}(\mathbb{R})$,
\begin{align*}
S_{R}f=(\chi_{[-R,R]}\widehat{f})^{\vee}=\dfrac{i}{2}\left(M_{-R}HM_{R}-M_{R}HM_{-R}\right)f,
\end{align*}
where $M_{a}$ is the operator defined by pointwise multiplication with $e^{2\pi i ax}$, for $a\in\mathbb{R}$. It it is evident that $M_{a}$ is a bounded operator $L^{p}\rightarrow L^{p}$, for $1\leq p\leq\infty$, with constant independent of $a$. For $f\in L^{1,\infty}(\mathbb{R})$ and $\lambda>0$ fixed,
\begin{align*}
\left|\left\{x\in\mathbb{R} : \left|M_{a}f(x)\right|>\lambda\right\}\right|=\left|\left\{x\in\mathbb{R} : \left|f(x)\right|>\lambda\right\}\right|\leq\dfrac{\left\|f\right\|_{L^{1,\infty}}}{\lambda},
\end{align*}
whence $M_{a}$ is a bounded operator $L^{1,\infty}\rightarrow L^{1,\infty}$ with constant independent of $a$.
I claim that $M_{a}HM_{-a}$ is uniformly weak type (1,1) bounded. For $\lambda>0$,
\begin{align*}
\left|\left\{\left|M_{a}HM_{-a}f\right|>\lambda\right\}\right|&=\left|\left\{\left|HM_{-a}f\right|>\lambda\right\}\right|\\
&\lesssim\dfrac{\left\|M_{-a}f\right\|_{L^{1}}}{\lambda}\\
&=\dfrac{\left\|f\right\|_{L^{1}}}{\lambda},
\end{align*}
where the implied constant is independent of $a$. Since by the triangle inequality,
\begin{align*}
\left\{\left|S_{R}f\right|>\lambda\right\}\subset\left\{\left|M_{-R}HM_{R}f\right|>\lambda\right\}\cup\left\{\left|M_{R}HM_{-R}f\right|>\lambda\right\},
\end{align*}
we conclude that $S_{R}$ is uniformly weak type $(1,1)$ bounded.
By the density of $\mathcal{S}(\mathbb{R})$ in $L^{1}(\mathbb{R})$, $S_{R}$ extends to a bounded operator $\widetilde{S_{R}}:L^{1}(\mathbb{R})\rightarrow L^{1,\infty}(\mathbb{R})$. To see that $\widetilde{S_{R}}f=S_{R}f$ a.e., when $f\in L^{1}(\mathbb{R})$, let $f_{n}\in\mathcal{S}(\mathbb{R})$ and $f_{n}\rightarrow f$ in $L^{1}(\mathbb{R})$, and observe that
\begin{align*}
\left|\left\{\left|S_{R}f-\widetilde{S_{R}}f\right|>\lambda\right\}\right|&\leq\limsup_{n\rightarrow\infty}\left|\left\{\left|S_{R}(f-f_{n})\right|>\dfrac{\lambda}{2}\right\}\right|+\left|\left\{\left|\widetilde{S_{R}}(f_{n}-f)\right|>\dfrac{\lambda}{2}\right\}\right|\\
&\lesssim\limsup_{n\rightarrow\infty}\dfrac{2\left\|f-f_{n}\right\|_{L^{1}}}{\lambda}\\
&=0,
\end{align*}
where we use that $\left\|S_{R}(f-f_{n})\right\|_{L^{\infty}}\leq R\left\|f-f_{n}\right\|_{L^{1}}\rightarrow 0, n\rightarrow\infty$. Since $\lambda>0$ was arbitrary, we conclude that $S_{R}f=\widetilde{S_{R}}f$ a.e. $\Box$

Theorem. For $f\in L^{1}(\mathbb{R})$, $S_{R}f\rightarrow f$ in measure, and there exists a subsequence $R_{k}\rightarrow\infty$, which depends on $f$, such that $S_{R_{k}}f\rightarrow f$ a.e.

Proof. First, observe that if $f\in \mathcal{S}(\mathbb{R})$, then it follows from Fourier inversion that
\begin{align*}
\left|S_{R}f(x)-f(x)\right|=\left|\int_{\left|\xi\right|\leq R}\widehat{f}(\xi)e^{2\pi i \xi x}\mathrm{d}\xi-\int_{\mathbb{R}}\widehat{f}(\xi)e^{2\pi i \xi x}\mathrm{d}\xi\right|\leq\int_{\left|\xi\right|>R}\left|\widehat{f}(\xi)\right|\mathrm{d}\xi,\quad\forall x\in\mathbb{R}
\end{align*}
Since $\widehat{f}\in L^{1}(\mathbb{R})$, the RHS tends to zero as $R\rightarrow\infty$. So $S_{R}f\rightarrow f$ uniformly.
Now assume $f\in L^{1}(\mathbb{R})$, fix $\delta>0$, and let $\epsilon>0$ be given. By the triangle inequality,
\begin{align*}
\left\{\left|S_{R}f-f\right|\geq\delta\right\}\subset\underbrace{\left\{\left|S_{R}(f-g)\right|\geq\dfrac{\delta}{3}\right\}}_{E_{1,R}}\cup\underbrace{\left\{\left|S_{R}g-g\right|\geq\dfrac{\delta}{3}\right\}}_{E_{2,R}}\cup\underbrace{\left\{\left|g-f\right|\geq\dfrac{\delta}{3}\right\}}_{E_{3}},
\end{align*}
where $g\in\mathcal{S}(\mathbb{R})$. Clearly, $\left|E_{3}\right|\leq 3\left\|f-g\right\|_{L^{1}}/\delta$. And by the uniform $L^{1}\rightarrow L^{1,\infty}$ boundedness of the operators $S_{R}$, we have that
\begin{align*}
\left|E_{1,R}\right|\lesssim\dfrac{3\left\|f-g\right\|_{L^{1}}}{\delta},\quad\forall R>0
\end{align*}
By density, we can choose $g$ so that $\left\|f-g\right\|_{L^{1}}<\delta\epsilon/9$. Now choose $R_{0}>0$ sufficiently large so that $E_{2,R}=\emptyset$ for all $R\geq R_{0}$. Putting these results together, we conclude that
\begin{align*}
\left|\left\{\left|S_{R}f-f\right|\geq\delta\right\}\right|\lesssim \dfrac{3(\delta\epsilon/9)}{\delta}+0+\dfrac{3(\delta\epsilon/9)}{\delta}<\epsilon,\quad\forall R\geq R_{0}
\end{align*}
Since $\mathbb{R}$ is a $\sigma$-finite measure space, convergence in measure implies converge a.e. of a subsequence. We conclude that there exists a subsequence $\left\{R_{k}\right\}$, which may depend of $f$, such that $S_{R_{k}}f\rightarrow f$ a.e. $\Box$


text:
Q: Build error caused by missing library arc4random I'm currently working on a Streaming framework, and decided to use ffmpeg to encode and or decode my Video and or Audio.
So i clicked through https://ffmpeg.org for the api files, and downloaded the statically linked version only to find out it actually contained a .exe (I use Windows in development, but plan on using Linux in production) instead of one or more dll's and header informations.
Since i don't think i can use the 'exe' as replacement for an dll, i cloned the git source, and tried to compile it myself.
Then, while compiling i run into this error:
CC  libavutil/random_seed.o
libavutil/random_seed.c: In function 'av_get_random_seed':
libavutil/random_seed.c:130:12: error: implicit declaration of function 'arc4random' [-Werror=implicit-function-declaration]
     return arc4random();
            ^
cc1: some warnings being treated as errors
common.mak:60: recipe for target 'libavutil/random_seed.o' failed
make: *** [libavutil/random_seed.o] Error 1

As far as I can tell, this means that I'm missing the library arc4random, so I started searching for this lib, and found absolutly nothing, besides the fact that this library is somehow Apple related..., but no dll's and stuff or sources to compile it myself.
I use cygwin and its GCC to compile on 64-Bit windows 7 Machine.
Can anyone hint me to some location where I can get this missing library, or some other possibility to get ffmpeg as library into my project?
(I would prefer something I can link statically , since this project is meant to be a lib by itself)
Maybe is there a way I can make use of that downloaded exe of ffmpeg, since i can borrow its headers from the source I cloned from Git?
Any Hint appreciated.
Best Regards,
Jannik Adam

A: This seems to be caused because the #if is incorrectly reporting that the system has this function. I was able to get around it by editing a couple of files.
Open libavutil/random_seed.c and look for #if HAVE_ARC4RANDOM, should be around line 129, and remove that block of three lines:
129 #if HAVE_ARC4RANDOM
130     return arc4random();
131 #endif

When you run make again you'll probably get another similar failure in time.c for gettimeofday(), so open libavutil/time.c and look for #if HAVE_GETTIMEOFDAY which should be around line 41 and remove the first block there, like this:
Before changing:
41 #if HAVE_GETTIMEOFDAY
42     struct timeval tv;
43     gettimeofday(&tv, NULL);
44     return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
45 #elif HAVE_GETSYSTEMTIMEASFILETIME

After changing:
41 #if HAVE_GETSYSTEMTIMEASFILETIME

After those two changes the compile got a lot further but failed on ffserver.c:
ffserver.c: In function 'main':
ffserver.c:4000:5: error: implicit declaration of function 'sigaction' [-Werror=implicit-function-declaration]
     sigaction(SIGCHLD, &sigact, 0);

To fix this error I opened config.mak and added -D_XOPEN_SOURCE=700 to the end of CFLAGS, like this:
42 CFLAGS=   -std=c99 -fomit-frame-pointer -pthread  -g -Wdeclaration-after-statement -Wall -Wdisabled-optimization -Wpointer-arith -Wredundant-decls -Wwrite-strings -Wtype-limits -Wundef -Wmissing-prototypes -Wno-pointer-to-int-cast -Wstrict-prototypes -Wempty-body -Wno-parentheses -Wno-switch -Wno-format-zero-length -Wno-pointer-sign -O3 -fno-math-errno -fno-signed-zeros -Werror=format-security -Werror=implicit-function-declaration -Werror=missing-prototypes -Werror=return-type -Werror=vla -Wformat -fdiagnostics-color=auto -Wno-maybe-uninitialized -D_XOPEN_SOURCE=700

This post explains a bit about why -D_XOPEN_SOURCE=700 helps.
Then I ran make again and it finally succeeded. After running make install all the binaries were put in place and I was able to successfully use it!


text:
Q: Ajax Uncaught TypeError: Cannot read property 'length' of undefined I want to populate my select box with json data from an external url.
I keep getting

Uncaught TypeError: Cannot read property 'length' of undefined

below is my json response
{"ecoachlabs":{
  "status":"201",
  "msg":"Form data loaded successfully.",
  "categories":[
    {"id":"2","category":"church"},{"id":"3","category":"financial institution"},
    {"id":"4","category":"old students association"},
    {"id":"1","category":"school"},
    {"id":"5","category":"tertiary"}
  ],
  "storage":[
    {"id":"1","category":"100MB"},{"id":"2","category":"250MB"},
    {"id":"3","category":"500MB"},{"id":"4","category":"2GB"},
    {"id":"5","category":"3GB"},{"id":"6","category":"5GB"}
  ]
  }}

below is my ajax post code
$(document).ready(function() {
  $("#institution_category").click(function() {

    var formData = {
      load_request_form_data: "1"
    }; //Array

    $.ajax({
      url: "http://api.ecoachlabs.com/v1/requests/api.php",
      type: "POST",
      data: formData,
      success: function(data, textStatus, jqXHR) {
        console.log(data.ecoachlabs.categories); //data - response from server
        $.each(data.categories, function(i, v) {
          $('#institution_category').append($('<option value="' + v.id + '">' + v.category + '</option>'));
        });
      },
      error: function(jqXHR, textStatus, errorThrown) {

      }
    });
  });
});

A: You do a console log of onsole.log(data.ecoachlabs.categories); and then use data.categories. Change data.categories to data.ecoachlabs.categories to parse the object correctly, otherwise you will get undefined. See the working snippet below please:

var formData = {
  load_request_form_data: "1"
}; //Array

$.ajax({
  url: "http://api.ecoachlabs.com/v1/requests/api.php",
  type: "POST",
  data: formData,
  success: function(data, textStatus, jqXHR) {
    console.log(data.ecoachlabs.categories); //data - response from server
    $.each(data.ecoachlabs.categories, function(i, v) {
      $('#institution_category').append($('<option value="' + v.id + '">' + v.category + '</option>'));
    });
  },
  error: function(jqXHR, textStatus, errorThrown) {

  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='institution_category'>

</select>

A: Check if exist before continue

if (!data || !data.length) return;

<script type="text/javascript">
        $(document).ready(function() {
        $("#institution_category").click(function(){

            var formData = {load_request_form_data:"1"}; //Array

            $.ajax({
                url : "http://api.ecoachlabs.com/v1/requests/api.php",
                type: "POST",
                data : formData,
                success: function(data, textStatus, jqXHR)
                {
                   if (!data || !data.length) return; // data not always exist or not always contains ecoachlabs/categories
                   console.log(data.ecoachlabs.categories);//data - response from server
                   $.each(data.categories, function(i, v){
                      $('#institution_category').append($('<option value="' + v.id + '">' + v.category + '</option>'));
                    });
                },
                error: function (jqXHR, textStatus, errorThrown)
                {

                }
            });
        });
        });
     </script>


text:
Q: Calculate time-based rolling average on multi-indexed dataframe I have a multi-indexed dataframe, which I group with a mask. Afterwards, I want to calculate the time-based rolling average.
time = pd.date_range('2000-05-01', freq='24H', periods=10)
mult_index = pd.MultiIndex.from_product([time, [0,1]], names=["time", "number"])
data = pd.DataFrame(range(20), index=mult_index)
mask = list(range(5)) * 4
data.groupby(mask).rolling("2d", on=mult_index.levels[0]).mean()

However, this raises the exception:
Traceback (most recent call last):
File "C:\Users\bi4372\.conda\envs\EnergyTimeSeriesFramework\lib\site-packages\IPython\core\interactiveshell.py", line 3331, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-77-e484a6b352eb>", line 1, in <module>
rolling.count()
File "C:\Users\bi4372\.conda\envs\EnergyTimeSeriesFramework\lib\site-packages\pandas\core\window\common.py", line 40, in outer
return self._groupby.apply(f)
File "C:\Users\bi4372\.conda\envs\EnergyTimeSeriesFramework\lib\site-packages\pandas\core\groupby\groupby.py", line 735, in apply
result = self._python_apply_general(f)
File "C:\Users\bi4372\.conda\envs\EnergyTimeSeriesFramework\lib\site-packages\pandas\core\groupby\groupby.py", line 751, in _python_apply_general
keys, values, mutated = self.grouper.apply(f, self._selected_obj, self.axis)
File "C:\Users\bi4372\.conda\envs\EnergyTimeSeriesFramework\lib\site-packages\pandas\core\groupby\ops.py", line 206, in apply
res = f(group)
File "C:\Users\bi4372\.conda\envs\EnergyTimeSeriesFramework\lib\site-packages\pandas\core\window\common.py", line 38, in f
return getattr(x, name)(*args, **kwargs)
File "C:\Users\bi4372\.conda\envs\EnergyTimeSeriesFramework\lib\site-packages\pandas\core\window\rolling.py", line 1969, in count
return self._apply(window_func, center=self.center, name="count")
File "C:\Users\bi4372\.conda\envs\EnergyTimeSeriesFramework\lib\site-packages\pandas\core\window\rolling.py", line 518, in _apply
return self._wrap_results(results, block_list, obj, exclude)
File "C:\Users\bi4372\.conda\envs\EnergyTimeSeriesFramework\lib\site-packages\pandas\core\window\rolling.py", line 331, in _wrap_results
final.append(Series(self._on, index=obj.index, name=name))
File "C:\Users\bi4372\.conda\envs\EnergyTimeSeriesFramework\lib\site-packages\pandas\core\series.py", line 292, in __init__
f"Length of passed values is {len(data)}, "
ValueError: Length of passed values is 10, index implies 4

Does anyone has an idea how to solve this issue? If I try it without an multi-index dataframe everything works:
time = pd.date_range('2000-05-01', freq='24H', periods=10)
data = pd.DataFrame(range(10), index=time)
mask = list(range(5)) * 2
data.groupby(mask).rolling("2d").mean()

Thanks in advance for your help.
EDIT 1 - Clearification of the question:
In the answer below DavideBrex proposes an approach to reset the index for solving this issue. However, a consequence of this solution would be that rows with number 0 will interfere with rows with number 1. I want to avoid this behaviour. See the following additional example:
time = pd.date_range('2000-05-01', freq='24H', periods=3)
mult_index = pd.MultiIndex.from_product([time, [0,1]], names=["time", "number"])
data = pd.DataFrame(range(6), index=mult_index)
data.columns=["col"]
mask = [0,0,1,1,0,1]
res = data.reset_index(level='number').groupby(mask).rolling('3d').mean()

The desired result would be
              number  col
  time
0 2000-05-01     0.0  0.0
  2000-05-01     1.0  1.0
  2000-05-03     0.0  4.0
1 2000-05-02     0.0  2.0
  2000-05-02     1.0  3.0
  2000-05-03     1.0  4.0

However, the true result is:
                number       col
  time
0 2000-05-01  0.000000  0.000000
  2000-05-01  0.500000  0.500000
  2000-05-03  0.000000  4.000000
1 2000-05-02  0.000000  2.000000
  2000-05-02  0.500000  2.500000
  2000-05-03  0.666667  3.333333

A: The problem is that the groupby gives groups of 4 rows:
for i, item in data.groupby(mask):
    print(item)

Gives:
                    0
time       number
2000-05-01 0        0
2000-05-03 1        5
2000-05-06 0       10
2000-05-08 1       15
                    0
time       number
2000-05-01 1        1
2000-05-04 0        6
2000-05-06 1       11
2000-05-09 0       16
.....      ..      ...

But you are then giving 10 values in the rolling function:
print(mult_index.levels[0])
DatetimeIndex(['2000-05-01', '2000-05-02', '2000-05-03', '2000-05-04',
               '2000-05-05', '2000-05-06', '2000-05-07', '2000-05-08',
               '2000-05-09', '2000-05-10'],
              dtype='datetime64[ns]', name='time', freq='24H')

Try this:
time = pd.date_range('2000-05-01', freq='24H', periods=10)
mult_index = pd.MultiIndex.from_product([time, [0,1]], names=["time", "number"])
data = pd.DataFrame(range(20), index=mult_index)
data.columns=["col"]
mask = list(range(5)) * 4
res = data.reset_index(level='number').groupby(mask).rolling('2d').mean()
res

Output:
    time    number  col
0   2000-05-01  0.0 0.0
0   2000-05-03  1.0 5.0
0   2000-05-06  0.0 10.0
0   2000-05-08  1.0 15.0
1   2000-05-01  1.0 1.0
1   2000-05-04  0.0 6.0
1   2000-05-06  1.0 11.0
1   2000-05-09  0.0 16.0
2   2000-05-02  0.0 2.0
2   2000-05-04  1.0 7.0
2   2000-05-07  0.0 12.0
2   2000-05-09  1.0 17.0
3   2000-05-02  1.0 3.0
3   2000-05-05  0.0 8.0
3   2000-05-07  1.0 13.0
3   2000-05-10  0.0 18.0
4   2000-05-03  0.0 4.0
4   2000-05-05  1.0 9.0
4   2000-05-08  0.0 14.0
4   2000-05-10  1.0 19.0

From answer


text:
Q: Hints to determine which combo boxes were selected? I have 8 combo boxes in an Access database. Each combo box can either have a value or not have a value (2 options). In total, there can be 256 combinations (2^8). I am trying to create some code in VBA that loops through these combinations to determine which combination currently exists, with the ultimate goal of writing an SQL query within VBA based on that combination. So for example, let's say combo1 and combo2 both have selections, but not combo3 through combo8. If that is the combination I would like my SQL query to do a SELECT FROM query WHERE a column in db = combo1 and a column in db = combo2. Can anyone provide hints as to how I would structure my code?
Thanks!

A: Dim a as string, b as string
const myAND as string = "AND "

a = ""
a = "SELECT * FROM a table "

b = ""
if cbo1.value <> "" then
  b = b & myAND & "AND field1 = '" & cbo1.value & "'"
end if

if cbo2.value <> "" then
  b = b & myAND & "field2 = '" & cbo2.value & "'"
end if

etc for each cbo box

If b <> "" Then

   ' Lazy way
   ' a = a & "WHERE 1=1 " & b

   ' remove the first AND way
   a = a & "WHERE 1=1 " & mid(b,len(myAND))

End if

' a now contains the SQL you need.

A: Dim where_condtion as String
Dim sqlquery as String

where_condtion = ""

IF combo1 <>"" then
    where_condtion = where_condtion + "~fieldname~ = " & combo1
End IF
IF combo2 <>"" then
    where_condtion = where_condtion + "AND ~fieldname~ = " & combo2
End IF
*
*
*
IF combo8 <>"" then
    where_condtion = where_condtion + "AND ~fieldname~ =" & combo8
End IF

IF where_condtion <> "" then
    sqlquery = "Select * from ~table name~ where" + where_condtion
ELSE
    sqlquery = "Select * from ~table name~
End IF

sqlquery = Replace(sqlquery, "where AND ", "where ")

DoCmd.OpenQuery "sqlquery", acViewNormal, acEdit

OR

CurrentDb.OpenRecordset("sqlquery")

A: Am option would be a concatenated string
Code Example
Dim strSQL as String
'basic string
strSQL = "SELECT tbl.fieldA, tbl.fieldB FROM tbl "

Dim strSQLwhere as String
strSQLwhere = ""
'Combobox cmbbox1
If Not isNull(cmbbox1) And cmbbox1.ListIndex <> -1 then
    strSQLwhere = strSQLwhere & "tbl.fieldToFilter1=" & cmbbox1
End if

'Combobox cmbbox2
If Not isNull(cmbbox2) And cmbbox2.ListIndex <> -1 then
    iF NOT strSQLwhere = "" then
       strSQLwhere = strSQLwhere & " AND "
    end if
    strSQLwhere = strSQLwhere & "tbl.fieldToFilter2=" & cmbbox2
End if

'And so on until cmbBox 8

'Combine all Strings
if not strSQLwhere = "" then
    strSQL  = strSQL  & " WHERE (" & strSQLwhere & ")"
End if

'Add here further thing like ORDER BY, GROUP BY
'Show SQL sting if it is well fomratted, change string concatenation if not
debug.print strSQL

You could do the combobox if-then-(else) cases in a separate function if you are able to do that in VBA.


text:
Q: (pandas) Create new column based on the presence or not of an element in groupby object I have a problem that is close to this one :
(pandas) Create new column based on first element in groupby object
So I have this dataframe:
     accidentID      cartype
0    58              70
1    58              -70
2    58              70
3    58              100
4    71              100
5    71              -70
6    250             70
7    250             70
8    250             100
9    250             70
10   70              70

What I want is to add a new column to show the car_in_the_wrong for a given accidentID knowing that :
if a cartype = -70 is present --> car_in_the_wrong = -70
if a cartype = 100 is present and no cartype = -70 --> car_in_the_wrong = 100
if 100 and -70 absent --> car_in_the_wrong = 70
     accidentID      cartype        car_in_the_wrong
0    58              70             -70
1    58              -70            -70
2    58              70             -70
3    58              100            -70
4    71              100            -70
5    71              -70            -70
6    250             70             100
7    250             70             100
8    250             100            100
9    250             70             100
10   300             70             70

Is there a way to do it with a groupby?
Thanks a lot!

A: Following this answer on how to Check if a value exists using multiple conditions within group in pandas, and taking advantage that statements with or are evaluated from left to right (i.e. the right-side part is not evaluated if the left-side holds True):
df['car_in_the_wrong'] = df['accidentID'].map(df.groupby('accidentID').apply(lambda x: x['cartype'].eq(-70).any()*-70 or x['cartype'].eq(100).any()*100 or x['cartype'].eq(70).any()*70))


text:
Q: How to get result from ControllerContext My controller action returns a custom ActionResult that executes either a success or failure result depending on some validation logic. This happens within ExecuteResult.
My question is, how can I check the result?
Here's the test so far:
[TestFixture]
public class FormActionResultTests
{
    TestController controller;

    [SetUp]
    public void SetUp()
    {
        ObjectFactory.Initialize(cfg =>
        {
            cfg.For<IFormHandler<TestModel>>().Use<TestModelHandler>();
        });

        controller = new TestControllerBuilder().CreateController<TestController>();
    }

    [Test]
    public void Valid_input_returns_success_result()
    {
        var result = controller.Test(new TestModel { IsValid = true, IsValid2 = true })
            .AssertResultIs<FormActionResult<TestModel>>();

        var context = controller.ControllerContext;

        result.ExecuteResult(context);
        // how to verify result?

    }
}

public class TestController : Controller
{
    public ActionResult Test(TestModel model) {
        return new FormActionResult<TestModel>(model, this.Content("Success"), View(model));
    }
}

public class TestModel {
    public bool IsValid { get; set; }
    public bool IsValid2 { get; set; }
}

public class TestModelHandler : IFormHandler<TestModel>
{
    public void Handle(TestModel form, IValidationDictionary validationDictionary)
    {

    }
}

Update
Here's what worked for me in the end (using NSubstitute):
    [Test]
    public void Valid_input_returns_success_result()
    {
        var result = new FormActionResult<TestModel>(new TestModel { IsValid = true, IsValid2 = true },
            new ContentResult { Content = "Success" }, new ContentResult { Content = "Failed" });

        var sb = new StringBuilder();
        var response = Substitute.For<HttpResponseBase>();
        response.When(x => x.Write(Arg.Any<string>())).Do(ctx => sb.Append(ctx.Arg<string>()));
        var httpContext = Substitute.For<HttpContextBase>();
        httpContext.Response.Returns(response);

        var controllerContext = new ControllerContext(httpContext, new RouteData(), new TestController());

        result.ExecuteResult(controllerContext);

        sb.ToString().ShouldEqual("Success");
    }

A: Controller should be tested that they return correct ActionResult in your case, and the Success or Failure of ActionResult should be tested by ActionResultTest and it has nothing to do with controller. Unit test means single unit test - but you test both controller and ActionResult in the same test, that is incorrect. To test ActionResult, first imagine that generally all that ActionResult does, is writing result to HttpResponse. Let's rewrite your code to use Moq to supply StringWriter for ControllerContext.HttpContext.HttpResponse.Output
[Test]
    public void Valid_input_returns_success_result()
    {
        var result = controller.Test(new TestModel { IsValid = true, IsValid2 = true })
            .AssertResultIs<FormActionResult<TestModel>>();

        var context = controller.ControllerContext;

        Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();

        StringWriter actionResultOutput = new StringWriter();

        mockHttpContext.Setup(x => x.Response.Output).Returns(actionResultOutput);

        context.HttpContext = mockHttpContext.Object;

        result.ExecuteResult(context);
        // how to verify result? Examine actionResultOutput

    }

All is left to examine actionResultOutput. For example, if your action result is designed to return string "Success" when validation is ok and "Error" when validation failed, compare these strings to actionResultOutput.ToString(). If your result view's generated html is more complex, you can use HtmlAgilityPack to examine output more deeply

A: You should write a simple unit test of the Test-action, asserting on the returned action result. You shouldn't depend on the MVC framework in your test. Simply create a new instance of TestController and call the Test method.