text:
Q: Associativity of Day convolution I'm trying to follow Day's argument to prove that $[\mathbf C,\mathbf{Sets}]$, where $\bf C$ is symmetric monoidal, is itself symmetric monoidal, but I'm stuck at the very beginning. Is there a way to prove that the convolution of two functors defines an associative "tensor" on $Psh(\mathbf C)$?
I apologize if the question seems too boring, please notice that

*

*Day's original paper is out of reach where I am;

*Google seems to give me nothing useful,

*As you can see, the nlab page lacks the proof of associativity.

If I try to write down $F\star G\star H$ in the two ways, I feel I have to exploit some kind of Yoneda lemma written in coend form, but I'm not such an expert on ''endy'' notation to find such a form out.
Thanks!

A: You are right that the Yoneda lemma plays the key role in the proof.
By the definition of convolution:
$$(F \otimes G) \otimes H \approx \int^{C, D} \left(\int^{A, B} F(A) \times G(B) \times \hom(C, A \otimes B)\right) \times H(D) \times \hom(-, C \otimes D)$$
Because products in $\mathbf{Set}$ preserve coends, the above is isomorphic to:
$$\int^{A, B, C, D} F(A) \times G(B) \times \hom(C, A \otimes B) \times H(D) \times \hom(-, C \otimes D)$$
The Yoneda lemma says that any covariant functor $K(A)$ is naturally isomorphic to $\hom(\hom(A, -), K)$. By definition, the last object is the end $\int_C K(C)^{\hom(A, C)}$. Therefore the Yoneda lemma says:
$$K(A) \approx \int_C K(C)^{\hom(A, C)}$$
By duality, we get the Yoneda lemma for contravariant functors $K$:
$$K(A) \approx \int^C K(C) \times \hom(A, C)$$
and from the perspective of the opposite category, for covariant functors $K$:
$$K(A) \approx \int^C K(C) \times \hom(C, A)$$
where the end turned into the coend and the exponent turned into the product.
In our case, we may reduce by Yoneda $\hom(C, A\otimes B)$ with $\hom(-, C \otimes D)$ under the coend:
$$\int^C \hom(-, C \otimes D) \times \hom(C, A\otimes B) \approx \hom(-, (A \otimes B) \otimes D)$$
obtaining:
$$\int^{A, B, D} F(A) \times G(B) \times H(D) \times \hom(-, (A \otimes B) \otimes D)$$
Due to associativity of $\otimes$ we know that $(A \otimes B) \otimes D \approx A \otimes (B \otimes D)$. Now it suffices to "unwind" the coend in the other direction.

A: The category of cocontinuous functors on $\widehat{C}$ with values in a cocomplete category is equivalent to the category of functors on $C$. In order to construct a natural isomorphism $(F \otimes G) \otimes H \cong F \otimes (G \otimes H)$ for $F,G,H \in \widehat{C}$, it is therefore enough to treat the case $F \in C$. Similarily, one reduces to $G \in C$ and $H \in C$. But then we use the associativity in $C$.


text:
Q: Need some help: _tkinter.TclError: couldn't recognize data in image file I need some help with Tkinter.
Even though my image file and code are in the same folder, I get the "_tkinter.TclError: couldn't recognize data in image file" error.
I've already gone through some of the other similar stack overflow questions without success; without using PIL, how can I resolve this issue?
Here is my code:
import tkinter as tk

root = tk.Tk()

canvas = tk.Canvas(root, height = 600, width = 1000)
canvas.pack()

frame = tk.Frame(root, bg = "purple")
frame.place(relx = 0.1, relwidth = 0.8, relheight = 1)

background_image = tk.PhotoImage(file = 'usMap.png')
background_label = tk.Label(root, image = background_image)
background_label.place(x = 0, y = 0, relwidth = 1, relheight = 1)

root.mainloop()

Thank you in advance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any way to import all the required Angular Material Classes? I am working on an Angular 2 project. Using Angular Material for designing purposes. Everytime I use a form module. I need to search for the classes that are required for that particular Module.
I just want to know if there is any way to import all the required classes for Angular material.
I am using angular cli for generation and packaging.
Using VS Code as IDE.

A: import { MaterialModule } from '@angular/material';

This module will import all angular material modules at instant, but you can use this until beta 10 only angular material team will deprecate this in beta 11.

Reminder that MaterialModule is deprecated and will be removed in a
  subsequent release (see changelog from beta.3 for more information).

https://github.com/angular/material2/blob/master/CHANGELOG.md

MaterialModule
MaterialModule (and MaterialRootModule) have been marked as
  deprecated. We've found that, with the current state of tree-shaking
  in the world, that using an aggregate NgModule like MaterialModule
  leads to tools not being able to eliminate code for components that
  aren't used.
In order to ensure that users end up with the smallest code size
  possible, we're deprecating MaterialModule, to be removed in the a
  subsequent release.
To replace MaterialModule, users can create their own "Material"
  module within their application (e.g., GmailMaterialModule) that
  imports only the set of components actually used in the application.

https://github.com/angular/material2/issues/3991
You can use this when beta 11 is up
import {
  MdAutocompleteModule,
  MdButtonModule,
  MdButtonToggleModule,
  MdCardModule,
  MdCheckboxModule,
  MdChipsModule,
  MdDatepickerModule,
  MdDialogModule,
  MdExpansionModule,
  MdFormFieldModule,
  MdGridListModule,
  MdIconModule,
  MdInputModule,
  MdListModule,
  MdMenuModule,
  MdNativeDateModule,
  MdPaginatorModule,
  MdProgressBarModule,
  MdProgressSpinnerModule,
  MdRadioModule,
  MdRippleModule,
  MdSelectModule,
  MdSidenavModule,
  MdSliderModule,
  MdSlideToggleModule,
  MdSnackBarModule,
  MdSortModule,
  MdTableModule,
  MdTabsModule,
  MdToolbarModule,
  MdTooltipModule,
  StyleModule,
 } from '@angular/material';
import { CdkTableModule } from '@angular/cdk/table';
import { A11yModule } from '@angular/cdk/a11y';
import { BidiModule } from '@angular/cdk/bidi';
import { OverlayModule } from '@angular/cdk/overlay';
import { PlatformModule } from '@angular/cdk/platform';
import { ObserversModule } from '@angular/cdk/observers';
import { PortalModule } from '@angular/cdk/portal';


text:
Q: Parsing json with retrofit2 gson-converter, with fields of another name I am trying to parse a json object which has field named "long", long is a keyword in java so I cannot use simple gson examples provided in retrofit page.
Should I create a custom converter or is there another way?

A: You can simply use @SerializedName. This is a Gson annotation which tells it how to serialize and deserialize the objects to json and vice-versa. You could have the following model:
public class YourModel {
   @SerializedName("long")
   @Expose
   private String theNameYouWantForYourVariable;
}

Note that I'm assuming it's a String, but you can use whatever data type you want and need. The @Expose annotation is not necessary, but recommended.
The key thing here is to notice the SerializedName annotation that takes the json's field name. Here's the javadoc


text:
Q: How to make best and SAFE jQuery form check Im' trying to reduce server load. Curently i use PHP form checks. Can somebody tell me best way to make SAFE javascript/jQuery form check? Any good examples?

A: If you're talking about reducing server load, the only way you can achieve that by javascript form valiadtion is to catch the errors early and thereby reduce the number of form submissions you will end up rejecting on the server side.
There are no javascript form validators - nor will there ever be - that will satisfy the SAFE condition to the point that you can reduce server load by means of removing the server side checks.
Thus, having dealt with the safe criteria, go ahead and use any jQuery validator you fancy. To that end, asking for preferred libraries is considered out of scope for Stack Overflow.


text:
Q: Entity Framework Fluent API: Violation of DRY? I just stumbled across an EF Code First tutorial that goes over creating POCO configurations using the Fluent API.  I was unaware this was available in EF and had only seem Data Annotations previously.
After watching this tutorial I read probably a dozen articles/topics on "Fluent API vs. Data Annotations".  It seems like the consensus is that Fluent API allows you to separate your "dumb" domain POCOs from your persistence logic.  The glaring problem I see with that is that you don't get the front-end validation that come along with the Data Annotations.  I have yet to read a response from the pro-Fluent API crowd as to how this is tackled.
When using Fluent API, are you forced to duplicate your logic in the configuration files as well as on the front-end?

A: Yes, when using the fluent API approach it's likely that you will end up duplicating entity metadata in your front-end validation.
One big benefit of the fluent API approach is that your entities have no dependency on Entity Framework. This issue has been fixed in .NET 4.5 by moving the data annotation attributes to the System.ComponentModel.DataAnnotations assembly.
It's also common with complex entity models, that your front-end will not actually use the domain entities, but will use DTOs or some front-end specific model projected from the entities. In this case you are going to lose your data annotation attributes anyway.


text:
Q: How to use the CSS attribute selector to select muliple elements? How can I use the CSS atribute selector to select multiple items? I need to hide some options written out by 3rd-party code on my site. In the example code below, I need to hide option 3, 4 and 6:
<select id="requestTypeSelect" name="requestType" required="required">
  <option value="" selected="selected" disabled="disabled">Type of Request *</option>
  <option value="1">Right to erasure</option>
  <option value="2">Right to access</option>
  <option value="3">Right to correct data</option>
  <option value="4">Right to data portability</option>
  <option value="5">Right to restrict use of personal data</option>
  <option value="6">Right to object to the use of personal data</option>
</select>

I can use the CSS below:
<style>
  /* hide options 3 5 and 6 */
  [value="3"] {
    display: none;
  }
</style>

which works when I target just 1 option, but when I try to hide others, no luck. I tried [value~="3 5 6"]based on what I'm reading from https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors but that doesn't work. I'm only able to hide a single item this way.
Any help would be greatly appreciated. thanks!


text:
Q: How to remove duplicates from collection using IEqualityComparer, LinQ Distinct I am unable to remove the duplicates from collection , i have implemented IEqualityComparer for the class Employee still i am not getting the output
static void Main(string[] args)
    {
        List<Employe> Employeecollection = new List<Employe>();

        Employeecollection.Add(new Employe("abc","def"));
        Employeecollection.Add(new Employe("lmn","def"));
        Employeecollection.Add(new Employe("abc", "def"));

        IEnumerable<Employe> coll = Employeecollection.Distinct(new Employe());

        foreach (Employe item in coll)
        {
            Console.WriteLine(item.fName + "   " + item.lName );
        }

    }

The Below is the Employee class implementation , here i implemented IEqualityComparer
class Employe : IEqualityComparer<Employe>
{
    public string fName { get; set; }
    public string lName { get; set; }

    public Employe()
    {

    }

    public Employe(string firstName, string LastName)
    {
        this.fName = firstName;
        this.lName = LastName;
    }

    #region IEqualityComparer<pcf> Members

    public bool Equals(Employe x, Employe y)
    {
        if (x.fName == y.fName && x.lName == y.lName)
        {
            return true;
        }

        return false;
    }

    public int GetHashCode(Employe obj)
    {
        return obj.GetHashCode();
    }

    #endregion
}

A: You need to override GetHashCode method in your Employee. You haven't done this. One example of a good hashing method is given below: (generated By ReSharper)
public override int GetHashCode()
{
    return ((this.fName != null ? this.fName.GetHashCode() : 0) * 397) ^ (this.lName != null ? this.lName.GetHashCode() : 0);
}

now after Distinct is called, foreach loop prints:
abc   def
lmn   def

In your case you are calling object's class GetHashCode, which knows nothing about internal fields.
One simple note, MoreLINQ contains DistinctBy extension method, which allows you to do:
IEnumerable<Employe> coll =
 Employeecollection.DistinctBy(employee => new {employee.fName, employee.lName});

Anonymous objects have correct implementation for both GetHashCode and Equals methods.

A: Here is a good tutorial
    public int GetHashCode(Employe obj)
    {
        return obj.fname.GetHashCode() ^ obj.lname.GetHashCode();
    }

A: The hashcode implementation is not correct:
public override int GetHashCode()
{
    return 13 * fName.GetHashCode() + 7 * lName.GetHashCode();
}

A: Forget IEqualityComparer and just use Linq directly:
EmployeeCollection.GroupBy(x => new{x.fName, x.lName}).Select(g => g.First());

A: Also it looks like your comparing by reference instead of content, hence the compare function doesn't work.
change it to use .Equals() instead of == and it should work.
example below:
#region IEqualityComparer<pcf> Members

public bool Equals(Employe x, Employe y)
{
    if (x.fName.Equals(y.fName) && x.lName.Equals(y.lName))
    {
        return true;
    }

    return false;
}

public int GetHashCode(Employe obj)
{
    return obj.GetHashCode();
}

#endregion

A: public int GetHashCode(Employe obj)
{
    return obj.GetHashCode();
}

For this method, return a hashcode of the properties that you are comparing for equality, instead of the object itself. Comparing the hashcode of the objects will always be false, so your list will never be filtered for duplicates.


text:
Q: Using selenium to scrape paginated table data (Python) I have this table: https://www.londonstockexchange.com/indices/ftse-aim-all-share/constituents/table?page=1. It's paginated I want to scrape all the content from the table starting from page 1 to the very end. I am trying to use the xpath but can't seem to get it to work.
Here is my code, any help welcome!
from selenium import webdriver
from selenium.webdriver.common.by import By

import os

# co.add_argument('--ignore-certificate-errors')
#co.add_argument('--no-proxy-server')
#co.add_argument("--proxy-server='direct://'")
#co.add_argument("--proxy-bypass-list=*")
co = webdriver.ChromeOptions()
co.add_argument('--headless')
driver = webdriver.Chrome(executable_path="C:/Users/user/Desktop/IG Trading/chromedriver.exe", chrome_options=co)
driver.get('https://www.londonstockexchange.com/indices/ftse-aim-all-share/constituents/table?page=1')
stock_names = driver.find_elements(By.XPATH, '/html/body/app-root/app-handshake/div/app-page-content/app-filter-toggle/app-ftse-index-table/section/table')
print(stock_names)

# for stock_name in stock_names:
#     print(stock_name)
#     text = stock_name.text
#     print(text)

A: This is one way you can obtain that information:
from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options as Firefox_Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support import expected_conditions as EC
import time as t
import pandas as pd
from tqdm import tqdm

firefox_options = Firefox_Options()

# firefox_options.add_argument("--width=1500")
# firefox_options.add_argument("--height=500")
# firefox_options.headless = True

driverService = Service('chromedriver/geckodriver')
browser = webdriver.Firefox(service=driverService, options=firefox_options)

big_df = pd.DataFrame()

browser.get('https://www.londonstockexchange.com/indices/ftse-aim-all-share/constituents/table')
try:
    WebDriverWait(browser, 3).until(EC.element_to_be_clickable((By.ID, "ccc-notify-accept"))).click()
    print('accepted cookies')
except Exception as e:
    print('no cookie button!')
t.sleep(2)

for i in tqdm(range(1, 40)):
    browser.get(f'https://www.londonstockexchange.com/indices/ftse-aim-all-share/constituents/table?page={i}')
    t.sleep(1)
    df = pd.read_html(WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "table[class='full-width ftse-index-table-table']"))).get_attribute('outerHTML'))[0]
    big_df = pd.concat([big_df, df], axis=0, ignore_index=True)

print(big_df)
big_df.to_csv('lse_companies.csv')
print('all done')
browser.quit()

This will display in terminal the big dataframe once all pages scraped, and also save it as a csv file on disk (in the same folder you are running your script from). Setup is Firefox/geckodriver on linux, however you can adapt it to your own, just observe the imports, and the logic after defining the browser/driver.
Selenium docs: https://www.selenium.dev/documentation/
TQDM: https://pypi.org/project/tqdm/


text:
Q: How to integrate PHP code with iOS code? This question might have broad scope. I actually don't have much idea about this.
I have tried to search this but I wasn't able to find a proper solution on my requirement.
I want to use some PHP code inside my iOS application.
Is it possible that I add some PHP code files inside my iOS app and call these files functions as per my requirement.
Hope this will give you an idea about my requirement.
Let me know if I need to put some more light on it.


text:
Q: Expo SDK 44 upgrade ERROR - App.js: [BABEL]: Unexpected token '.' I have recently upgraded my app from SDK 40 to SDK 44 and came across this error App.js: [BABEL]: Unexpected token '.' (While processing: /Users/user/path/to/project/node_modules/babel-preset-expo/index.js)
Error Stack Trace:
App.js: [BABEL]: Unexpected token '.' (While processing: /Users/user/path/to/project/node_modules/babel-preset-expo/index.js)
/Users/user/path/to/project/node_modules/babel-preset-expo/index.js:48
        ...(options?.jsxRuntime !== 'classic' && {
                    ^

SyntaxError: Unexpected token '.'
    at wrapSafe (internal/modules/cjs/loader.js:931:16)
    at Module._compile (internal/modules/cjs/loader.js:979:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
    at Module.load (internal/modules/cjs/loader.js:879:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Module.require (internal/modules/cjs/loader.js:903:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at loadCjsDefault (/Users/user/path/to/project/node_modules/@babel/core/lib/config/files/module-types.js:85:18)
    at loadCjsOrMjsDefault (/Users/user/path/to/project/node_modules/@babel/core/lib/config/files/module-types.js:57:16)

Here is my babel.config.js:
return {
    presets: ['babel-preset-expo', { jsxRuntime: 'automatic' }],
    plugins: [
        ['inline-dotenv'],
        ['.....']
    ]
}

Here is my package.json:
{
    "main": "node_modules/expo/AppEntry.js",
    "scripts": {
        "start": "expo start",
        "android": "expo start --android",
        "ios": "expo start --ios",
        "web": "expo start --web",
        "eject": "expo eject",
        "test": "jest"
    },
    "jest": {
        "preset": "jest-expo"
    },
    "dependencies": {
        "@babel/plugin-transform-react-jsx": "^7.16.5",
        "@react-native-async-storage/async-storage": "~1.15.0",
        "@react-native-community/art": "^1.2.0",
        "@react-native-community/datetimepicker": "4.0.0",
        "@react-native-community/masked-view": "0.1.10",
        "@react-native-community/netinfo": "7.1.3",
        "@react-native-community/push-notification-ios": "^1.2.2",
        "@react-native-community/slider": "4.1.12",
        "@react-navigation/native": "^5.1.4",
        "aws-amplify": "^3.3.1",
        "aws-amplify-react-native": "^4.2.6",
        "axios": "^0.19.2",
        "expo": "^44.0.0",
        "expo-app-loading": "~1.3.0",
        "expo-barcode-scanner": "~11.2.0",
        "expo-camera": "~12.1.0",
        "expo-constants": "~13.0.0",
        "expo-font": "~10.0.4",
        "expo-linking": "~3.0.0",
        "expo-mail-composer": "~11.1.0",
        "expo-notifications": "~0.14.0",
        "expo-permissions": "~13.1.0",
        "expo-secure-store": "~11.1.0",
        "expo-sqlite": "~10.1.0",
        "expo-updates": "~0.11.2",
        "expo-web-browser": "~10.1.0",
        "file-saver": "^2.0.2",
        "jsbarcode": "^3.11.3",
        "link": "^0.1.5",
        "metro-config": "^0.64.0",
        "npm": "^8.3.0",
        "qs": "^6.9.4",
        "react": "17.0.1",
        "react-dom": "17.0.1",
        "react-native": "https://github.com/expo/react-native/archive/sdk-44.0.0.tar.gz",
        "react-native-barcode-expo": "^1.1.1",
        "react-native-elements": "^3.2.0",
        "react-native-fs": "^2.16.6",
        "react-native-gesture-handler": "~2.1.0",
        "react-native-modal": "^11.5.6",
        "react-native-modal-datetime-picker": "^8.6.0",
        "react-native-paper": "^3.10.1",
        "react-native-push-notification": "^3.5.2",
        "react-native-reanimated": "~2.3.1",
        "react-native-router-flux": "^4.2.0",
        "react-native-safe-area-context": "3.3.2",
        "react-native-screens": "~3.10.1",
        "react-native-snap-carousel": "^3.9.1",
        "react-native-svg": "12.1.1",
        "react-native-web": "0.17.1",
        "react-navigation-animated-switch": "^0.6.4",
        "react-navigation-drawer": "^2.4.11",
        "react-navigation-header-buttons": "^3.0.5",
        "react-router-dom": "^6.0.0-alpha.3",
        "yarn": "^1.22.17"
    },
    "devDependencies": {
        "@babel/core": "^7.12.9",
        "@babel/runtime": "^7.9.2",
        "@react-native-community/eslint-config": "^0.0.7",
        "babel-jest": "^25.1.0",
        "babel-plugin-inline-dotenv": "^1.6.0",
        "babel-preset-expo": "9.0.1",
        "eslint": "^6.8.0",
        "expo-cli": "^5.0.2",
        "jest": "^26.6.3",
        "jest-expo": "^44.0.0",
        "metro-react-native-babel-preset": "^0.66.2",
        "react-test-renderer": "^16.13.1"
    },
    "private": true
}

Any help will be greatly appreciated.

A: can you give your

*

*package.json

*node version

I think that's because of the babel issue / your node version, because it cannot transpile the optional chaining https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
maybe tried using latest LTS node version? because as far as I know, the latest LTS node version already support optional chaining

A: Just to let you know, it's a bug in babel-preset-expo when you are using Node 12.

Optional chainning is not supported in node12 and can be easily replaced with extra checks

https://github.com/expo/expo/pull/15545

A: From what I can see, Expo SDK 44 is still in beta.
The Error Stack Trace reads that newer syntax (in this case the optional chaining operator ?.) isn't being transpiled by Babel which causes the failure.
Simply downgrading to the stable SDK 43 should solve all issues.
P.S: This error has been reported to Expo already by the beta testers.

A: If you use expo v44 you have to update babel-preset-expo dev dependency to v9.0.2:
"babel-preset-expo": "9.0.2",

A: Downgrading to SDK 43.0.0 worked fine for me:
expo update 43.0.0


text:
Q: Android Image Rotation: Ending it at a random position I am new to android. I want to rotate an image and i want it to stop rotating at a random position. I have the following code. The image rotates infinitely. I'm having problems to stop it at a random position.
RotateAnimation anim = new RotateAnimation(0f,360f,55f,55f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(80);

// Start animating the image

iv.startAnimation(anim);

A: Set this parameter as per your requirement
anim.setRepeatCount(50);

The following line in your code makes the anim run infinitely.
anim.setRepeatCount(Animation.INFINITE)

Change your RotateAnimation as
RotateAnimation anim = new RotateAnimation(0f,generateRandomNumber(),55f,55f);
anim.setFillAfter(true);

public float generateRandomNumber() {

    Random rand = new Random();
    int randomNum = rand.nextInt((360 - 0) + 1);

    return (float)randomNum;
}


text:
Q: SWupdate ERROR: No suitable .swu image found I am rather new to eclipse hawkbit and SWupdate I have been trying to do a test implementation on a RPi before I go with the production implementation.
I have Hawkbit up and running but I am having several problems with SWupdate, I have built a core-image-full-cmdline.wic and the .swu update Image along with it:
This is the local.conf:
MACHINE = "raspberrypi3"

IMAGE_FSTYPES += "wic"

RPI_USE_U_BOOT = "1"

KERNEL_IMAGETYPE = "uImage"

IMAGE_INSTALL_append = " kernel-image kernel-modules"

#WKS_FILES_raspberrypi3 = "ts-raspberrypi.wks"

PREFERRED_PROVIDER_u-boot-fw-utils = "libubootenv"

DISTRO_FEATURES_append = " systemd"

DISTRO_FEATURES_BACKFILL_CONSIDERED += "sysvinit"

VIRTUAL-RUNTIME_init_manager = "systemd"

VIRTUAL-RUNTIME_initscripts = "systemd-compat-units"

ENABLE_UART = "1"

I also got this error when I changed the IMAGE_FSTYPE from ext4 rpimg to wic:
ERROR: update-image-1.0-r0 do_swuimage: swupdate cannot find image file: /home/aswin/yocto/build/tmp/deploy/images/raspberrypi3/core-image-full-cmdline.ext4.gz
ERROR: Logfile of failure stored in: /home/aswin/yocto/build/tmp/work/raspberrypi3-poky-linux-gnueabi/update-image/1.0-r0/temp/log.do_swuimage.87006
ERROR: Task (/home/aswin/yocto/layers/meta-swupdate-boards/recipes-extended/images/update-image.bb:do_swuimage) failed with exit code '1'

So I had to change the update-image.bb FSTYPE = ".wic"
And when I comment this out #WKS_FILES_raspberrypi3 = "ts-raspberrypi.wks"
Then flash the image to a sd card and boot it nothing really shows up except for a blinking line. If I leave it, then the .swu file is way too big to upload it to hawkbit.

A: How do you expect it to work when you have HW compatibility errors, JSON file corrupted errors, forget about the hawkbit for now, and try to see if your sw-description file is creating the correct swu image file that updates the rootsfs or whatever you want to update using mongoose webserver and only then move on to the hawkbit.
First solve the errors that are coming before

suitable .swu image not found

Edited: please also put the sw-descirption file that you are using to create your swu file for further help.


text:
Q: Extract the formula for stepwise optimized regression model I performed a multiple linear regression. My real dataframe contains a lot of more x-values.
Regression <- lm(df1$y ~ df2$x1 + df2$x2 + df2$x3 + df2$x4 + df2$x5 + df2$x6)

StepRegression=step(Regression,direction="both")

#Or with the MASS package
library(MASS)
step.model <- stepAIC(Regression, direction = "both", trace = FALSE)
step.model

My question is now, how do I automatically get the optimized model? I tired this:
library(MASS)
OptiRegression = step.model$call

But this only gives me this:
lm(formula =df1$y ~ df2$x1 + df2$x3 + df2$x5)

summary(test)
Length  Class   Mode
     2   call   call

But I want to get the summary of the updated model, with the coefficients which I get for example when I typ in:
OptiRegression = lm(df1$y ~ df2$x1 + df2$x3 + df2$x5)
summary (OptiRegression)

A: I believe you are trying to do something like any of the following two regressions. I will use the built-in dataset mtcars since you have not posted one.
library(MASS)

Regression <- lm(mpg ~ ., data = mtcars)

StepRegression <- step(Regression, direction = "both")

OptiReg1 <-StepRegression$terms
fit1 <- lm(OptiReg1, data = mtcars)

As you can see, both summaries are equal, only the formula changes.
summary(StepRegression)
summary(fit1)

Or with the MASS package, function stepAIC.
step.model <- stepAIC(Regression, direction = "both", trace = FALSE)

OptiReg2 <- step.model$terms
fit2 <- lm(OptiReg2, mtcars)

Now, once again, these two summaries are in practice equal, only the formula changes. And it changes because in fit2 what is passed is OptiReg.
summary(step.model)
summary(fit2)


text:
Q: Mongoose ODM, BreezeJS - one model definition is there any "ready to you" solution how to export mongoose models to client side app? If I imagine perfect world, mongoose models would let me define which properties and methods of entity is needed on client side and generates needed classes for client so I can easily use them with BreezeJS for example.
Any idea? Or is it road to hell combine it together? :))

A: Update - As of v 1.2.7 - we have provided two facilities that will help accomplish tasks like this.

*

*The Breeze metadata format has been documented and any json object that adheres to this format and is returned from the breeze metadata call will be used to configure breeze's client side metadata.

*The JsonResultsAdapter may be used to reshape or assist with interpreting the result of any web service call so that any results returned by the call can become Breeze entities.

--- Previous post
Please stay tuned, we will be releasing a new version of breeze in the next few days with support for pluggable json adapters that will allow the consumption of any web service.  And since breeze metadata can already be defined for an arbitrary model, you should be able to consume your mongoose models pretty easily. Of course, the devil IS in the details.


text:
Q: Firebase error 403. Your client does not have permission to access this url Dears
I'm having issue with my firebase lately. My app uses firebase authentication. Sometimes it works fine, but some times when I try to get OTP, I get error. After that even if I try to access firebase website from same device browser, I get the error 403. Your client does not have permission to access this URL. Means I cannot access firebase from that device at all.
Note that I'm in a country where we have restricted internet access and I have to use VPN to access many sites, including firebase. After few trials, when I change VPN servers, I can again access firebase in my browser, but as soon as I try using my app, it blocks again.
I have seached a lot on this issue, but couldn't find any solution. Most of the solutions are related to firebase cloud access, but in my case I cannot access firebase at all.
Please also note that I have tried using simulators as well as tried using my mobile for testing.
If you need any further details on the issue, please let me know.
PS: I'm a flutter developer and authentication is working fine if firebase access is not blocked.


text:
Q: Solve for $x$: $2^x=4x$ Given that $x$ is a positive integer. By using methods of trial and error as well as plotting two lines: $y=2^x$, $y=4x$ on a graph and find their intersection point, we can easily solve for $x$ which is equal to 4. However, I do not know how to solve this using only equation. Can anyone help me?

A: Prove that $2^x>4x$ for $x > 4$ by induction. It's very easy since:
$2^{x+1}>4(x+1)$ equivalent to $2^x + 2^x> 4x + 4x$

A: In the first place, $4$ is a solution but not the only solution. There is still another solution that lies at about $0.31$.
In the second place, there is no effective way to find analytic solutions for this equation using only the equation. As mentioned in the comments, $4$ is a good integer, we stumble on it and find it just fits exactly good. But $0.309\cdots$ is a "bad" number and there is no possibility we'd stumble on it.
However there is a numerical way that we can approach the $0.309\cdots$ solution as close as we desire. To do this, we can make use of the contraction mapping principle. Just note that $\phi(x)=2^x/4$ is a contraction on the Banach space $[0,2^{4/\ln2}]$ (you can check the Lipschitz constant), you can arbitrarily pick a $x_0$ within this interval and get the (only) fixed point $x*$ via iteration:
$$x_n=\phi(x_{n-1}),\,x*=\lim_{n\to\infty}x_n$$
which is just the desired solution.


text:
Q: Loading different data in array So I got this array setup called tableDateArray, which is defined in SubClass.h. Now im trying to change the data of the array on wether or not a button is selected.
My code in MainView.m:
- (IBAction)dateSpecifiedButtonTouch:(id)sender {

if (monthly.enabled == NO){
    NSLog(@"no");
    tableDateArray = [NSArray arrayWithObjects:
                      @"January 2012",
                      @"February 2012",
                      @"March 2012",
                      @"April 2012",
                      @"May 2012",
                      @"June 2012",
                      @"July 2012",
                      @"August 2012",
                      @"September 2012",
                      @"Octobre 2012",
                      @"November 2012",
                      @"December 2012",
                      @"All months",
                      nil];
    }

if (monthly.enabled == YES){
    NSLog(@"yes");
    tableDateArray = [NSArray arrayWithObjects:
                      @"2002",
                      @"2003",
                      @"2004",
                      @"2005",
                      @"2006",
                      @"2007",
                      @"2008",
                      @"2009",
                      @"2010",
                      @"2011",
                      @"2012",
                      @"All years",
                      nil];
}}

So the NSlog is tracing the correct value so that's not the issue. But my array will be filled with whatever state is selected first and is refusing to change the data. Im sure im overlooking something simple.
Added per request:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell"; // unused method of type cell.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [tableDateArray objectAtIndex:indexPath.row];
return cell;
}

I dont think im calling reloaddata to be honest.

A: From the code provided till now it looks ok .No reason can be said from why not it is working
May be this is a little more right way to write the code
- (IBAction)dateSpecifiedButtonTouch:(id)sender {
    if (monthly.enabled)
    {
        NSLog(@"yes");
        tableDateArray = [NSArray arrayWithObjects:
                          @"2002",
                          @"2003",
                          @"2004",
                          @"2005",
                          @"2006",
                          @"2007",
                          @"2008",
                          @"2009",
                          @"2010",
                          @"2011",
                          @"2012",
                          @"All years",
                          nil];
    }
    else
    {
        NSLog(@"no");
        tableDateArray = [NSArray arrayWithObjects:
                          @"January 2012",
                          @"February 2012",
                          @"March 2012",
                          @"April 2012",
                          @"May 2012",
                          @"June 2012",
                          @"July 2012",
                          @"August 2012",
                          @"September 2012",
                          @"Octobre 2012",
                          @"November 2012",
                          @"December 2012",
                          @"All months",
                          nil];

    }
[table reloadData];
}

EDIT :
Ok for that purpose let me say there is 2 ViewControllers VC1, VC2
in VC1 you are updating the value and in VC2 the table with datasource array named inputArray.

*

*So in VC1 when button pressed

*Get the instance of vc2

*assign the array to VC2instance.inputArray=tableDataArray;

*Call refresh in table with reloadData

A: Geez... so many answers have it all wrong.
Just call [yourTableViewOutlet reloadData] from the IBAction where the monthly button is being touched.
E.G.
- (IBAction)dateSpecifiedButtonTouch:(id)sender {
    ...
    ...
    ...
    ...
    [yourTableViewOutlet reloadData];
}

Of course you'll want to change "yourTableViewOutlet" to the true name of your table view that you've connected to an outlet.

A: - (IBAction)dateSpecifiedButtonTouch:(id)sender {

    if (monthly.enabled == NO){
        NSLog(@"no");
        tableDateArray = [[NSMutableArray alloc ]initWithObjects:
                          @"January 2012",
                          @"February 2012",
                          @"March 2012",
                          @"April 2012",
                          @"May 2012",
                          @"June 2012",
                          @"July 2012",
                          @"August 2012",
                          @"September 2012",
                          @"Octobre 2012",
                          @"November 2012",
                          @"December 2012",
                          @"All months",
                          nil];
    }

    if (monthly.enabled == YES){
        NSLog(@"yes");
        tableDateArray = [[NSMutableArray alloc ]initWithObjects:
                          @"2002",
                          @"2003",
                          @"2004",
                          @"2005",
                          @"2006",
                          @"2007",
                          @"2008",
                          @"2009",
                          @"2010",
                          @"2011",
                          @"2012",
                          @"All years",
                          nil];
    }}

A: - (IBAction)dateSpecifiedButtonTouch:(id)sender {
    //maybe toggle monthly.enabled here?
    [yourTableView reloadData];

}
static NSArray * tableDateArray = nil;
static NSArray * tableYearArray = nil;
+(void)initialize
{
     if(self == [MyCLass class])
     {
           tableDateArray = [[NSMutableArray alloc ]initWithObjects:
                          @"January 2012",
                          @"February 2012",
                          @"March 2012",
                          @"April 2012",
                          @"May 2012",
                          @"June 2012",
                          @"July 2012",
                          @"August 2012",
                          @"September 2012",
                          @"Octobre 2012",
                          @"November 2012",
                          @"December 2012",
                          @"All months",
                          nil];

           tableYearArray = [[NSMutableArray alloc ]initWithObjects:
                          @"2002",
                          @"2003",
                          @"2004",
                          @"2005",
                          @"2006",
                          @"2007",
                          @"2008",
                          @"2009",
                          @"2010",
                          @"2011",
                          @"2012",
                          @"All years",
                          nil];
     }
}

//all of your tableview delegates/data sources:
{
     NSArray * dataSource;

     dataSource = monthly.enabled ? tableDateArray : tableYearArray;
     //use datasource as the datasource
}

A: I fixed my problem by using the reloadData as suggested. However, the reloadData had to be called in viewWillAppear otherwise it refused to update my tableView.
Code:
- (void)viewWillAppear:(BOOL)animated{
    [self.tableView reloadData];
}


text:
Q: How to get a div that fills the entire screen based on Bootstrap I am using the bootstrap  to wrap my code into using ruby on rails. Now within this parent class, I'd like to add a div (see blue div example on screenshot) that fills entire screen. But it doesn't work, as it keeps the padding of the container div. What to do? The relevant cod is:
In application.html.erb I have

<%= yield %>

In my view file I have

Lorem

A: Add css in the view  as:-

Lorem

If the css do not work after adding in this way, then add !important with the css.
Eg:-

Lorem


text:
Q: POSTing to session-validate.jsp not playing with WSO2 ELB I came across an issue using WSO2 Stratos 1.6.0 when trying to browse the registry. The browser just hangs when clicking on Resources > Browse. Having a look at the network traffic I see an HTTP POST request to /carbon/admin/jsp/session-validate.jsp that doesn't complete.
I then started debugging the org.apache.synapse.transport.passthru.ServerWorker (2.1.1-wsov1) in the WSO2ELB (2.0.2). I found that the code that writes the ACK to the response output stream is being skipped. This only appears to happen when POSTing to /carbon/admin/jsp/session-validate.jsp, when I hacked the /carbon/admin/js/main.js to perform a GET, everything worked fine.
So my question(s) being... is this a bug in main.js? is it a bug in ServerWorker in WSO2ELB? is there a special reason that the sessionAwareFunction in main.js uses POST as opposed to GET?

A: This is a bug in the transport ELB uses. Please use the latest release ELB http://wso2.com/products/elastic-load-balancer/


text:
Q: Ratio of Volume of Standard Simplex to its Dual In the two-dimensional case, the ratio of the area of an equilateral triangle whose vertices are the mid-points of the edges of another equilateral triangle is 1/4th.  For a tetrahedron and its dual, the ratio is known to be 1/27.
In the general case, is it $\frac{1}{n^{n}}$?  By general case, I mean the standard simplex $S$ in $\mathbb{R}^n$ and the simplex whose vertices are the Euclidean barycenters of the faces of $S$.

A: I think the key is to take the $n$th power of the ratio of the side lengths.
In what follows, I'll view the $n$-simplex as living in $\mathbb{R}^{n + 1}$ with vertices the standard basis vectors.
First, the outer simplex always has side length $\sqrt{2}$.
To get the side length of the inner simplex, we can compute the distance between the midpoints of two different faces. Since these midpoints occur at the average of $n - 1$ of the vertices, they have one coordinate 0 and the other $n$ equal to $1 / n$. Therefore the distance between two of them is $\sqrt{\frac{1}{n^2} + \frac{1}{n^2}} = \frac{\sqrt{2}}{n}$.
So, the ratio of the side lengths is
\begin{align*}
\frac{\frac{\sqrt{2}}{n}}{\sqrt{2}} = \frac 1 n ,
\end{align*}
and the $n$-volumes have ratio $1 / n^n$ as you claimed.

A: The barycenter of an $n$-simplex is the average of all the vertices: $O=\frac{1}{n+1}(V_1+\ldots+V_{n+1})$. The barycenter of the face opposite $V_i$ is the average of all the vertices except $V_i$: $W_i=\frac{1}{n}[(V_1+\ldots+V_{n+1})-V_i]=\frac{n+1}{n}O-\frac{1}{n} V_i$. So $O=\frac{n}{n+1}W_i+\frac{1}{n+1}V_i$. This means that $O$ lies on the segment $V_iW_i$ and divides it in ratio $n:1$ (this is a generalization of the fact that the point of intersection of the medians divides each median in the ratio of $2:1$). Therefore the "dual" simplex is obtained from the original one by a similarity transform centered at $O$ and with ratio $-\frac{1}{n}$. Since we are in $n$ dimensions, this multiplies the volume by $\frac{1}{n^n}$.
In fact this is true for $n$-volume any $n$-simplex in arbitrary $\mathbb{R}^m$, with same proof.


text:
Q: Retrieve ODBC table and Insert into SQL Server CE database I have an ODBC connection to a database of which I need one table of data. The table has about 20 rows, and a couple thousand lines of data.
I intend to insert this table into my local SQL Server CE database, where I can put it to further use.  Both connections have been tested and work.
My attempt was at just inserting one column to keep things simple (I'm new to C#, programming, and stackoverflow).
OdbcConnection c = new OdbcConnection(ConnectionString1);
SqlCeConnection d = new SqlCeConnection(ConnectionString2);

c.Open();
d.Open();

string sqlC = "SELECT * FROM ODBCTABLE WHERE ODBCCOLUMN='12345'";
OdbcCommand commandC = new OdbcCommand(sqlC, c);

string sqlD = "INSERT INTO SQLCETABLE(SQLCECOLUMN) VALUES (@sql)";
SqlCeCommand commandD = new SqlCeCommand(sqlD, d);

OdbcDataReader reader = commandC.ExecuteReader();

while (reader.Read())
{
  string x = reader[0].ToString();
  commandD.Parameters.Add("@sql",SqlDbType.NVarChar, 5).Value = x;
  commandD.ExecuteNonQuery();
}

c.Close();
c.Dispose();

d.Close();
d.Dispose();

I get the error The SqlCeParameter with this name is already contained by this SqlCeParameterCollection.

*

*Why is this wrong?

*Is there a way to fix this?

*Are there better ways to do this
    transfer? (I believe sqlbulktransfer does not exist for odbc)

*Being my first post on Stackoverflow, did I go about posting a
        question correctly?

A: Change this part of your code
commandD.Parameters.Add("@sql",SqlDbType.NVarChar, 5);
while (reader.Read())
{
  string x = reader[0].ToString();
  commandD.Parameters["@sql"].Value = x ;
  commandD.ExecuteNonQuery();
}

The problem arises because, in every loop, you repeat the add of the same named parameter to the collection resulting in the error above.
Moving the creation of the parameter outside the loop and updating only the value inside the loop should resolve the error.
Yes, I think you have posted the question correctly.


text:
Q: Algorithm Not Allowed error with Firebase trying to decode JWT token I am having a lot of issues trying to decrypt a JWT token using php and Firebase
<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require 'vendor/autoload.php';

use \Firebase\JWT\JWT;

try {
    $key = 'MYKEY';
    $token = $_POST['id_token'];
    $data = JWT::decode($token, $key, array('HS256'));
} catch (\Exception $e) {
    echo $e;
}

?>

Algorithm not allowed in JWT.php:97
Has anyone ever had this?
Paul

A: If I am not wrong, in recent versions of JWT the decode function requires a new parameter (allowed algorithms). Previously this was not required.
I use this to get all supported algorithms:
$decoded = JWT::decode($token, $key, array_keys(JWT::$supported_algs));

A: You should use the google keys to decode the token.
$googleKeysURL = 'https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com';
$key = json_decode(file_get_contents($googleKeysURL), true);

$decoded = JWT::decode($token, $key, array("RS256"));

Also I was having a problem because of the server timezone so I add this before the decoding line:
JWT::$leeway = 600;


text:
Q: OpenCL program on amazon EC2 hanging at the end I have a OpenCL C++ program that I'm running on a NVIDIA GPU-enabled EC2 instance. Quite often, at the end of the program, it hangs, and I end up having to stop the instance to get out of it.
Here is the end of my code, is there something that I should be doing differently?
/* Finalization */
ret = clFlush(command_queue);
printf("clFlush: %s\n", getErrorString(ret));
ret = clFinish(command_queue);
printf("clFinish: %s\n", getErrorString(ret));
ret = clReleaseMemObject(ymobj);
printf("clReleaseMemObject: %s\n", getErrorString(ret));
ret = clReleaseProgram(program);
printf("clReleaseProgram: %s\n", getErrorString(ret));
ret = clReleaseKernel(kernel);
printf("clReleaseKernel: %s\n", getErrorString(ret));
ret = clReleaseCommandQueue(command_queue);
printf("clReleaseCommandQueue: %s\n", getErrorString(ret));
ret = clReleaseContext(context);
printf("clReleaseContext: %s\n", getErrorString(ret));

free(source_str);

free(y);

exit(0);

Typically I can see that the output from the command following clFinish, but nothing after that.


text:
Q: Manually Controlling DFP Ad Selection and Display We want to add to our existing DFP enabled site an alphabetical listing of our advertisers, via custom creatives for this list, and by taking advantage of the existing working custom targeting. We would like to do this entirely using DFP as it already has the advertiser reports and we want to incorporate the impression count and click-through rates for these listings in the existing reports to our advertisers.
In pseudo-code it would be something like:
googletag.setTargeting( "key", "value" );
SessionStore<Array> adList = googletag.getAds();
SessionStore<int> offset = 0;

// optionally sort adList by Advertiser Name, or other metadata
for ( int i = 0; i < 10; i++ ) {
    var adItem = adList[offset + i];
    document.write( '<div id="ad_id_' + adList.adID + '"' );
    googletag.defineSlot( networkIDplus, [custom creative size], 'ad_id_" + adList.adID );
}
// store remainder for 'next' page
offset = 10;

This way if there were 18 custom creative for the advertisers, we could display 10 on the first page, and then the remaining 8 on a second view.
Looking at the DFP API – it appears that is designed for ad management only, and not display. Looking at the Google Publisher Tag API, it does not support targeting specific ads for display or returning lists of ads.
As an alternative, using a page of 10 tags and then a 'refresh' does not make sense as we would not be able to guarantee that the listing is clean and in order without duplicates.
Is there something I'm missing from Google/DFP or does anyone have a workaround so that we can paginate ads and control which ads are display where and when?
Thanks in advance.

A: I only have a work around I'm afraid...
To get a specific creative to display in a specific space all the time, you'd have to create an Ad Unit for each slot on the UI and traffic a single lineitem + creative through it.
(You could dynamically assign the Ad Unit ID but that's about as elegant as it gets).
1: Create an ad unit, (override to deselect adsense just to be safe)
2: Create a line item with a single creative and assign to the adUnit
type = sponsorship or house
Goal = 100% impressions
Pretty high level description let me know if you need more detail.


text:
Q: Bootstrap Nested Table (Grid) I am new to bootstrap and I have a requirement to develop hierarchical grid with two levels; basically I need this kind of implementation with bootstrap table
http://www.trirand.net/aspnetmvc/grid/hierarchytwolevels
I search on the web and could not find any good resource with bootstrap hierarchical grid. Is there any possibility to implement hierarchical grid with bootstrap?

A: We have used html table, bootstrap and jquery datatable. here is the link how to develop nested datatable
http://www.codeproject.com/Articles/189621/Creating-an-expandable-master-details-table-jQuery


text:
Q: Including and excluding globbing patterns in bash I am trying to use the PHPCompatibility standard for PHP CodeSniffer to test a specific set of files.
I'm currently using find to do this.
find ./path1 ./path2 ./path3 ./path4                                                \
    -type f                                                                         \
    -name '*.php'                                                                   \
    -not -path './path4/dontwantthis/*'                                             \
    -exec ./vendor/bin/phpcs                                                        \
    --standard=PHPCompatibility --runtime-set testVersion 5.6 {}                    \;

However, this is really slow and inefficient because the startup for the script runs for every single file.
The phpcs script takes in a path like ./vendor/bin/phpcs --standard=PHPCompatibility --runtime-set testVersion 5.6 <path-of-your-php-files> and I'd like to find a way to replicate the find stuff with a globbing pattern in place of the <path-of-your-php-files>
One of the major problems I was having was including ./path4/*.php while also excluding ./path4/dontwantthis/*

A: End your -exec option with + instead of \;. That tells find to run the command once with all the filenames, rather than separately for each filename.
find ./path1 ./path2 ./path3 ./path4                                                \
    -type f                                                                         \
    -name '*.php'                                                                   \
    -not -path './path4/dontwantthis/*'                                             \
    -exec ./vendor/bin/phpcs                                                        \
    --standard=PHPCompatibility --runtime-set testVersion 5.6 {} +


text:
Q: System.Web.helpers.json encode UTC datetime issue Using MVC5 & jquery, i'm trying to handle a known issue of datetime conversion problem with the json ecoding.
on my view, i'm using the following line to create a json object on the view:
@Html.Hidden("boxJson", Html.Raw(System.Web.Helpers.Json.Encode(item)));

everything works prefect, since this 'item' im encoding is a complex object containing some inner classes, but the encoding works prefect, EXCEPT the datetime. i already managed to handle the enclosed string (ex: /Date(1078729200000)/) for a date on the client side with some client functions. but couldn't handle the UTC issue that this Encode function does to dates.
[for those who are no familiar with it, the Encode function handles Datetime coming from DB, where the datetime has the property kind is set to Unspecified, as UTC time automatically.]
I know i might do some work around and manipulate the dates in the json by some client function, but im using the whole json object POSTing it back to the server without interfering.
var jsonObject =  $('#boxJson').val();
$.ajax({
                url: 'some url\Func',
                type: 'POST',
                data: jsonObject ,
                contentType: "application/json; charset=utf-8",

[HttpPost]
public JsonResult Func(Class jsonObject ){
//jsonObject comes with all class and inner class members BUT dates are in UTC timezone
...
}

which, again works fine, except of the UTC datetime.
I've tried to use:
 @Html.Hidden("boxJson" , Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(item)));

which fixed the date problem, but couldn't handle my complex 'item' object.
basically, i'm looking for a way to override the Json.Encode method with some method that handles the UTC datetime issue.
or any other workaround will be helpful as well.
UPDATE
my complex class 'item':
public class ScheduleResult : IComparable<ScheduleResult>
    {
        public bool Succeeded { get; set; }
        public int Position { get; set; }
        public ServiceRequest Request { get; set; }
        public ProviderResource AssignedResource { get; set; }
        public DateTime Start { get; set; }
        public DateTime Finish { get; set; }
        public ScheduleEvaluation ScheduleEvaluation { get; set; }
        public int Ranking { get; set; }
    }

ServiceRequest , ProviderResource , ScheduleEvaluation are also classes.

A: Well, after some more coding, i figured that my problem using Json.NET was derived classes i have, in my example: ServiceRequest, ProviderResource are of this kind.
so the Json.NET needs the attributes [DataContract] for the class, and [DataMemeber] for each class property to be able to serialize the class.


text:
Q: Can't insert current date to new row $query = "INSERT INTO user (user_name, user_password, user_email, user_joindate)
          VALUES ('$username', '$password', '$email', CURDATE())";

$result=mysqli_query($currentConnection, $query) or die ("Could not insert into database.");

It connects to the database just fine and It's hitting the or die error (could not insert).
user_joindate type is ''DATE'' because I don't want irrelevant hour times. Already tried now() and current_timestamp, doesn't work.
edit: the problem is in the user_joindate query because when I remove it, the whole query works, despite the user_joindate receving a bunch of zeros.

A: if you want to store current date than set default value is CURDATE() function in insert query
like
CREATE TABLE Orders
(
OrderId int NOT NULL,
ProductName varchar(50) NOT NULL,
OrderDate datetime NOT NULL DEFAULT CURDATE(),
PRIMARY KEY (OrderId)
)

insert query
INSERT INTO Orders (ProductName) VALUES ('Jarlsberg Cheese')

A: Can you write here an error message from mysql? If you don't know how to get error message just rewrite your code like this:
if(!mysqli_query($currentConnection, $query)) {
    echo mysqli_error($currentConnection);
}

Without an error message nobody is not able to answer you correctly

According to the error output that you paste to the comment, your query tries to insert the same value for the unique field twice. It seems your user_id field is primary but not auto-increment. Just do it an auto-increment than try to insert again. The user_id field will be set a unique value each time.

A: Simple you just change data type of user_joindate field and set  TIMESTAMP data type and also not need to insert value when you add record
like this way
$query = "INSERT INTO user (user_name, user_password, user_email)
          VALUES ('$username', '$password', '$email')";

$result=mysqli_query($currentConnection, $query) or die ("Could not insert into database.");

A: For the database error you got from the unsuccessful saving of CURDATE() into your table, you can either alter the column that's causing the error or you manually provide a value for that to avoid duplication.
If you want to change your user_id column, you can do this:
//this is incremental
ALTER TABLE user CHANGE user_id user_id INT(10) AUTO_INCREMENT PRIMARY KEY;

If you want providing an id manually, make sure your user_id datatype is in char/varchar/... and your query be like:
$query = "INSERT INTO user (user_id, user_name, user_password, user_email, user_joindate) VALUES (uuid(), '$username', '$password', '$email', CURDATE())";

And just a warning not to use mysql_* now for it is deprecated
  officially as of PHP 5.5 and has been removed entirely as of PHP 7.0.
  Try using the latest ones like PDO/Mysqli to avoid having
  problems in the  future.


text:
Q: Populating a spreadsheet from other tab values In Excel for Mac:
I have 2 tabs (wkst1 and wkst2) and need to populate a third one (wkst3)
wkst1 has one column with names listed
e.g.
A

B

wkst2 has two columns
X     1

Y     4

I need to populate wkst3 to ensure all rows in wkst2 are associated to each name listed in wkst1.
e.g. my wished result would be:
A     X     1

A     Y     4

B     X     1

B     Y     4

Can you suggest the code I should use?

A: I managed to solve the problem on my own.
Sub writeall()

    Dim Ws As Worksheet
    Dim Ws1 As Worksheet
    Dim Ws2 As Worksheet

    Dim X As Long
    Dim Y As Long
    Dim count As Long

    Application.ScreenUpdating = False

    Set Ws = ActiveWorkbook.Worksheets(1)
    Set Ws1 = ActiveWorkbook.Worksheets(2)
    Set Ws2 = Workbooks("xxxx.xlsx").Sheets("2017") ' xxxx is the name of the xlsx

    count = 1

    For X = 2 To Ws2.Range("A" & Rows.count).End(xlUp).Row
        For Y = 1 To Ws1.Range("A" & Rows.count).End(xlUp).Row
            count = count + 1
            Ws.Cells(count, 1).Value = Ws2.Cells(X, 1).Value
            Ws.Cells(count, 2).Value = Ws1.Cells(Y, 2).Value
            Ws.Cells(count, 3).Value = Ws1.Cells(Y, 1).Value

        Next Y
    Next X

    Application.ScreenUpdating = True
    MsgBox ("Spreadsheet updated")

End Sub


text:
Q: Copy and update record expression doesn't work I'm trying to copy an entity in a table using LinqPad.
let dc = new TypedDataContext()
let title = "Some title"

let newestUser= dc.UserIDs |> Seq.filter (fun(x)->x.Funktion="SomeFunction") |> Seq.last

let newUser=  {newestUserwith Title= title}

The type 'UserID' does not contain a field 'Title'
But Title is a public field. I'm seeing it in the list by using GetFields()
Has anyone any idea what the reason of that is?

A: The with keyword is used to copy and update F# records. A record is a dumb set of fields containing values and no internal state, which is easy to copy. It cannot work on normal objects since there is no defined way to copy any given object.
The error message given by F# when trying to use this syntax on a normal object is The record label 'Title' is not defined. It would be more helpful if it was 'newestUser' is not a record.


text:
Q: no fontmanager in java.library.path The following code works just fine on my desktop:
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setFont(new Font("SansSerif", Font.BOLD, 18));

        Graphics2D graphics = (Graphics2D) g;
        graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        graphics.drawString(s, 5, 20);

However, when I run this code on my server (openjdk running on linux alpine within a Docker container), it fails with the following error:
java.lang.UnsatisfiedLinkError: no fontmanager in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1867)
at java.lang.Runtime.loadLibrary0(Runtime.java:870)
at java.lang.System.loadLibrary(System.java:1122)
at sun.font.FontManagerNativeLibrary$1.run(FontManagerNativeLibrary.java:61)
at java.security.AccessController.doPrivileged(Native Method)
at sun.font.FontManagerNativeLibrary.<clinit>(FontManagerNativeLibrary.java:32)
at sun.font.SunFontManager$1.run(SunFontManager.java:339)
at java.security.AccessController.doPrivileged(Native Method)
at sun.font.SunFontManager.<clinit>(SunFontManager.java:335)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at sun.font.FontManagerFactory$1.run(FontManagerFactory.java:82)
at java.security.AccessController.doPrivileged(Native Method)
at sun.font.FontManagerFactory.getInstance(FontManagerFactory.java:74)
at java.awt.Font.getFont2D(Font.java:491)
at java.awt.Font.access$000(Font.java:224)
at java.awt.Font$FontAccessImpl.getFont2D(Font.java:228)
at sun.font.FontUtilities.getFont2D(FontUtilities.java:180)
at sun.java2d.SunGraphics2D.checkFontInfo(SunGraphics2D.java:669)
at sun.java2d.SunGraphics2D.getFontInfo(SunGraphics2D.java:830)
at sun.java2d.pipe.GlyphListPipe.drawString(GlyphListPipe.java:50)
at sun.java2d.pipe.ValidatePipe.drawString(ValidatePipe.java:165)
at sun.java2d.SunGraphics2D.drawString(SunGraphics2D.java:2928)

java -version (on my server) gives:
openjdk version "1.8.0_77-internal"
OpenJDK Runtime Environment (build 1.8.0_77-internal-alpine-r0-b03)
OpenJDK 64-Bit Server VM (build 25.77-b03, mixed mode)

I searched for awt libs and they could be found here:
/usr/lib/jvm/java-1.8-openjdk/jre/lib/amd64/libawt_headless.so
/usr/lib/jvm/java-1.8-openjdk/jre/lib/amd64/libawt.so

A: I ran into this exact same problem running Alpine Linux 3.4. I solved the problem by following the directions in this github issue:

*

*Install the JRE with GUI support, i.e. openjdk8-jre instead of openjdk8-jre-head

*Install the fontconfig and ttf-dejavu packages

The RUN line in my Dockerfile looks like:
RUN apk add openjdk8-jre fontconfig ttf-dejavu

After this, the JDK was able to load the default fonts automatically, and the exception went away.

A: I ran into the same issue with my docker image for which I used Java 11 app base which does not have GUI libraries installed. I got the error like no font manager and the cause for that error is -> it is failing to read/create font using awt library.
When used the java stretch image with GUI support the error gone away.


text:
Q: Witt vectors and maps of $\lambda$-rings Consider the ring $W(\mathbb{F}_p)$ of big Witt vectors of $\mathbb{F}_p$. This has a natural structure of a $\lambda$-ring (in the strong sense) since rings of big Witt vectors always do.
$\mathbb{Z}_p$ also has the structure of a $\lambda$-ring, given by the maps $\lambda^n(x)= \binom{x}{n}$.
There is a canonical quotient map (of rings) $W(\mathbb{F}_p) \to \mathbb{Z}_p$ from the big Witt vectors to the classical $p$-adic Witt vectors. Is this a $\lambda$-ring homomorphism?  More generally, when (if ever) do we get a $\lambda$-ring structure on the smaller $p$-adic Witt vectors?
I know this quotient map admits an additive section. We could potentially use this to define $\lambda$ operators on the ring of $p$-adic Witt vectors, but it is not clear to me that this would actually give the structure of a $\lambda$-ring. And in my particular case, it is unclear if this would agree with the $\lambda$-ring structure I already have.

A: I think the answer is ``No'' for $p$ odd.
Stronger yet, there exists no $\lambda$-ring structure on $\mathbb{Z}_{p}$
under which the canonical quotient map $W\left(  \mathbb{F}_{p}\right)
\rightarrow\mathbb{Z}_{p}$ becomes a $\lambda$-ring morphism. However, due to
the manifold occasions for mistakes and misunderstandings in my argument,
please check it thoroughly.
Let $p$ be an odd prime. Let $\Lambda$ be the Hopf algebra of symmetric
functions over $\mathbb{Z}$ (in the indeterminates $x_{1},x_{2},x_{3},\ldots
$). It is known that $\Lambda$ carries further structures, such as plethysm,
inner multiplication and inner comultiplication. I am using the material of
Michiel Hazewinkel's Witt vectors, part 1 here (although not always his
notations: my $\Lambda$ is his $\mathbf{Symm}$, and my $x_{1},x_{2}
,x_{3},\ldots$ are his $\xi_{1},\xi_{2},\xi_{3},\ldots$).
Fix a commutative ring $\mathbf{k}$. The $\lambda$-ring of big Witt vectors
$W\left(  \mathbf{k}\right)  $ is defined as the set $\operatorname*{Ring}
\left(  \Lambda,\mathbf{k}\right)  $ of all ring homomorphisms from
$\Lambda\rightarrow\mathbf{k}$, endowed with an addition that comes from the
comultiplication of $\Lambda$, an additive inverse that comes from the
antipode of $\Lambda$, a multiplication that comes from the inner
comultiplication of $\Lambda$, and a $\lambda$-ring structure that comes from
the plethysm of $\Lambda$.
We let $p_{1},p_{2},p_{3},\ldots$ be the power sum symmetric functions in
$\Lambda$ (that is, $p_{n}=\sum_{i\geq1}x_{i}^{n}$). I am sorry for using the
letter $p$ which already stands for a prime, but this is a standard (and the
$p$ in ``$p_{1},p_{2},p_{3},\ldots$'' always
comes with a subscript).
We let $w_{1},w_{2},w_{3},\ldots\in\Lambda$ be the ``Witt
vector coordinate'' symmetric functions in $\Lambda$; these
are recursively defined by the power-series equality
$\prod_{d\geq1}\left(  1-w_{d}t^{d}\right)  ^{-1}=\prod_{i\geq1}\dfrac
{1}{1-x_{i}t}\in\mathbb{Z}\left[  \left[  x_{1},x_{2},x_{3},\ldots\right]
\right]  \left[  \left[  t\right]  \right]  $.
(These $w_{1},w_{2},w_{3},\ldots$ are called $x_{1},x_{2},x_{3},\ldots$ in
§9.63 of Hazewinkel's notes. For a quick overview of their properties,
see Exercise 2.79 in Victor Reiner and YHS, Hopf Algebras in Combinatorics, arXiv:1409.8356v3.) Let $\Lambda^{\prime}$ be the subring of $\Lambda$
generated by $w_{p^{0}},w_{p^{1}},w_{p^{2}},\ldots$. Then, the restriction map
$\operatorname*{Ring}\left(  \Lambda,\mathbf{k}\right)  \rightarrow
\operatorname*{Ring}\left(  \Lambda^{\prime},\mathbf{k}\right)  $ is
(equivalent to) the canonical quotient map $W\left(  \mathbf{k}\right)
\rightarrow W_{p}\left(  \mathbf{k}\right)  $ from the big Witt vectors
$W\left(  \mathbf{k}\right)  $ to the $p$-typical Witt vectors $W_{p}\left(
\mathbf{k}\right)  $.
It is well-known that $p_{n}=\sum_{d\mid n}dw_{d}^{n/d}$ for every positive
integer $n$. In particular, $p_{p^{k}}=\sum_{i=0}^{k}p^{i}w_{p^{i}}^{p^{k-i}}$
for every $k\in\mathbb{N}$. From this, it is easy to see that for every
$k\in\mathbb{N}$,
(1) there exists a positive integer $N$ such that $Nw_{p^{k}}$ is a
polynomial in $p_{p^{0}},p_{p^{1}},\ldots,p_{p^{k}}$ with no constant term.
We now define two ring homomorphisms $\alpha:\Lambda\rightarrow\mathbf{k}$ and
$\beta:\Lambda\rightarrow\mathbf{k}$ by setting
$\alpha\left(  f\right)  =f\left(  1,0,0,0,\ldots\right)  $ and $\beta\left(
f\right)  =f\left(  -1,0,0,0,\ldots\right)  $ for every $f\in\Lambda$
(where the $1$ and the $-1$ are taken in $\mathbf{k}$). (Incidentally,
$\alpha$ is the internal counit of $\Lambda$.)
Now, $\alpha+\beta$ is the ring homomorphism $\Lambda\rightarrow\mathbf{k}$ satisfying
$\left(  \alpha+\beta\right)  \left(  f\right)  =f\left(  1,-1,0,0,0,\ldots
\right)  $ for every $f\in\Lambda$.
Thus, it is easy to see that $\left(  \alpha+\beta\right)  \left(
p_{i}\right)  =0$ for every odd $i\geq1$. In particular, $\left(  \alpha
+\beta\right)  \left(  p_{p^{i}}\right)  =0$ for every $i\in\mathbb{N}$. Thus,
from (1) we see that $\left(  \alpha+\beta\right)  \left(  w_{p^{k}
}\right)  =0$ for every $k\in\mathbb{N}$ as long as all positive integers are
invertible in $\mathbf{k}$. But we can remove the ``all
positive integers are invertible in $\mathbf{k}$'' condition
(because proving $\left(  \alpha+\beta\right)  \left(  w_{p^{k}}\right)  =0$
for $\mathbf{k}=\mathbb{Z}$ is sufficient to ensure that $\left(  \alpha
+\beta\right)  \left(  w_{p^{k}}\right)  =0$ holds for every $\mathbf{k}$).
Hence, we obtain $\left(  \alpha+\beta\right)  \left(  w_{p^{k}}\right)  =0$
for every $k\in\mathbb{N}$. In other words, the canonical quotient map
$W\left(  \mathbf{k}\right)  \rightarrow W_{p}\left(  \mathbf{k}\right)  $
sends $\alpha+\beta$ to the zero of the ring $W_{p}\left(  \mathbf{k}\right)
$.
On the other hand, recall that the $\lambda$-ring structure on $W\left(
\mathbf{k}\right)  $ comes from plethysm on $\Lambda$. More precisely,
$\left(  \lambda^{n}\gamma\right)  \left(  f\right)  =\gamma\left(
e_{n}\left[  f\right]  \right)  $ for every $n\geq1$, $\gamma\in W\left(
\mathbf{k}\right)  $ and $f\in\Lambda$,
where $e_{n}\left[  f\right]  $ denotes the plethysm of $f$ into $e_{n}$
(denoted by $e_{n}\circ f$ in Hazewinkel's notes). Applying this to
$n=2$, $\gamma=\alpha+\beta$ and $f=p_{1}$, we obtain
$\left(  \lambda^{2}\left(  \alpha+\beta\right)  \right)  \left(
w_{1}\right)  =\left(  \alpha+\beta\right)  \left(  \underbrace{e_{2}\left[
w_{1}\right]  }_{=e_{2}}\right)  =\left(  \alpha+\beta\right)  \left(
e_{2}\right)  $
$=e_{2}\left(  1,-1,0,0,0,\ldots\right)  =-1$.
Assume now that $\mathbf{k}\neq0$. Thus, $\left(  \lambda^{2}\left(
\alpha+\beta\right)  \right)  \left(  w_{1}\right)  =-1\neq0$. Hence, the
canonical quotient map $W\left(  \mathbf{k}\right)  \rightarrow W_{p}\left(
\mathbf{k}\right)  $ sends $\lambda^{2}\left(  \alpha+\beta\right)  $ to a
nonzero element of the ring $W_{p}\left(  \mathbf{k}\right)  $.
Thus, the canonical quotient map $W\left(  \mathbf{k}\right)  \rightarrow
W_{p}\left(  \mathbf{k}\right)  $ sends $\alpha+\beta$ to zero, but
$\lambda^{2}\left(  \alpha+\beta\right)  $ to a nonzero element. Therefore,
there exists no $\lambda$-ring structure on $W_{p}\left(  \mathbf{k}\right)  $
under which this canonical quotient map $W\left(  \mathbf{k}\right)
\rightarrow W_{p}\left(  \mathbf{k}\right)  $ becomes a $\lambda$-ring
morphism. Now, applying this to $\mathbf{k}=\mathbb{F}_{p}$ and recalling that
$W_{p}\left(  \mathbb{F}_{p}\right)  \cong\mathbb{Z}_{p}$, we see that there
exists no $\lambda$-ring structure on $\mathbb{Z}_{p}$ under which the
canonical quotient map $W\left(  \mathbb{F}_{p}\right)  \rightarrow
\mathbb{Z}_{p}$ becomes a $\lambda$-ring morphism. As I said, this is all
under the assumption that $p$ is odd, but I would not expect even $p$ to
behave much different.


text:
Q: Is there a TailMap implementation in Python like in Java? There is a Java implementation of TreeMap, which contains a method called tailMap as described here: https://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html
Is there a corresponding built-in library or third-party library for Python?
As far as I know, this python library implements tree map, but does not implement tailMap -- https://pypi.org/project/sortedcontainers

A: As far as I can see, there doesn't exist a built-in library, however there are a few built-in utility functions that can help us to make an quick implementation of it. Here's my quick go at it:
# tailMap.py
x = {'b': 1, 'c': 2, 'e': 3, 'a': 4, 'd': 5}

def tail_map(m, key):
    keys = sorted(m)
    keys = keys[keys.index(key):]
    return {k: m[k] for k in keys}

print(f'{tail_map(x,"c")=}')

This gave me:
> python tailMap.py
> tail_map(x,"c")={'c': 2, 'd': 5, 'e': 3}

Edit: A similar function should be adaptable to the library you referenced.


text:
Q: Retreiving a datasnapshot from Firebase reference I'm trying to retrieve some data from my public Firebase database, wherein I store a simple highscore list. My problem is that onDataChange() is never actually called or fails to do anything.
Below is part of my code, which is called in a method that runs every time a certain activity is created:
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    Log.i(TAG_FIREBASE_READER_HIGHSCORE , ref.child("highscore-list").toString());

    ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.i(TAG_FIREBASE_READER_HIGHSCORE , "entered onDataChange for FirebaseReader");
            Toast.makeText(fromContext, "Reading online highscores, please wait...", Toast.LENGTH_LONG).show();

            for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                Log.i(TAG_FIREBASE_READER_HIGHSCORE, "found child " + snapshot.toString());
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.i(TAG_FIREBASE_READER_HIGHSCORE, "onCancelled was called");
        }

    });

In my logcat output I get that onCancelled is called, but not onDataChange. I have confirmed that the reference is right, by getting the reference to spit out the child "highscore-list" in the logcat, which provides the correct output (I can resolve it).
I'm not using any kind of Firebase authentication, so my database rules look like this:
{
  "rules": {
    "users": {
      "$uid": {
        ".read": true,
        ".write": true
      }
    }
  }
}

How do I actually retrieve any data from my database if this doesn't work?

A: *

*Make sure you have the internet connection permission

*Firebase automatically denies acess if you dont specificy security rules for a path, so if you are not reading data from a user in with your security rules, it will fail
{
  "rules": {
    ".read": true,
    ".write": true
  }
}


text:
Q: iOS FTP concurrent upload and download I am trying to write a code in which i have to create 2 parallel threads (Which is running inside a dispatch serial queue) 1 thread will upload and another thread will download the file from the server. Both of the upload and download progress is going to be updated on another screen with bytes upload and downloaded.
But I am facing some strange issues:-

*

*As soon as I create secondary threads my functions returns to the dispatch Serial Queues and it starts another serial task scehduled instead of waiting for 2 current parallel Tasks to complete first.

*As soon as the Download Threads starts the upload Thread Stops uploading file and returns -1 during Writeto server.
I am using Apple SimpleFTP example and trying to run it in 2 parallel threads 1 is for put and second for get.
Any Idea why the Upload stops while downloading file from server(I have made 2 different connnections to FTP server as well)
Advance Thanks for any help.

A: solved the issue using the Syncronous FTP request. The run loop run function was blocking the other thread from calling the stream delegate function.


text:
Q: want to replace with regex in notepad++ I have a text file with content similar to the following. I want to remove all text between Bank Applicants (the numeric strings) using the find-and-replace functionality of Notepad++.
0004829 01-02 000421
0004830 01-02 000422
0466608 06-47 000743
Bank sl. no beginning with an 'IA' indicates ICB account
Paramount Textile Limited Page No: 143 of 258
Lottery Conducted by--Dept. of Electrical and Electronic Engineering, BUET. Date:03/10/2013
General
Applicants
0004823 01-02 000415
0004824 01-02 000416
0004826 01-02 000418
0004829 01-02 000421
0004830 01-02 000422
0004831 01-02 000423
0004832 01-02 000424
Bank sl. no beginning with a
Lottery Conducted by--Dept. of Electrical and Electronic Engineering, BUET. Date:03/10/2013
General
Applicants
0004823 01-02 000415
0004829 01-02 000421
0004830 01-02 000422
0004831 01-02 000423
0004832 01-02 000424
0004839 01-02 000431
0004840 01-02 000432
Bank sl. no beginning with an 'IA' indicates ICB account
and Electronic Engineering, BUET. Date:03/10/2013
General
Applicants
0004823 01-02 000415
0004830 01-02 000422
0004831 01-02 000423
0004832 01-02 000424
0004839 01-02 000431

An example of the output I want is as follows:
0004829 01-02 000421
0004830 01-02 000422
0466608 06-47 000743
0004823 01-02 000415
0004824 01-02 000416
0004826 01-02 000418
0004829 01-02 000421
0004830 01-02 000422
0004831 01-02 000423
0004832 01-02 000424
0004823 01-02 000415
0004829 01-02 000421
0004830 01-02 000422
0004831 01-02 000423
0004832 01-02 000424
0004839 01-02 000431
0004840 01-02 000432
0004823 01-02 000415
0004830 01-02 000422
0004831 01-02 000423
0004832 01-02 000424
0004839 01-02 000431

A: Put notepad ++ search and replace in regex mode and search for ^[^0-9].*\r\n replace with you should leave blank
make sure . does not match new line Picture below of settings and output

A: Instead of Find go to Mark tab. Find all lines that match "^000", enable option "Bookmark line", and click "Mark all". All lines similar to "0004829 01-02 000421" will be bookmarked.
Now remove all remaining lines: Search > Bookmark > Remove unmarked lines.
EDIT: Instead of "^000" better use "^[0-9]{3}".

A: Regex to find anything other than your bank account numbers looks like:
^((?!\d{7}\s\d{2}-\d{2}\s\d{6}).)*$

This searches for anything other than 7 digits followed by a space and then 2 digits followed by a hyphen and then other 2 digits and another space and 6 final digits.
You can use this to Mark all the lines that match this pattern and then remove the Marked Lines.

A: Using vim, the regex would be :
g/^Bank/,/^Applicants/d

A: Have a try with:
Find what: Bank.+?Applicants\r?\n
Replace with: <nothing>
then click on Replace all.
Make sure you have checked Regular expression  and dot matches newline


text:
Q: http component can't connect to proxy I'm trying to connect to a website through a proxy, but I'm getting an error
Error Code: 407 Proxy Authentication Required. Forefront TMG requires authorization to fulfill the request. Access to the Web Proxy filter is denied. (12209)

My code is very close to the example that apache provides, https://hc.apache.org/httpcomponents-client-ga/examples.html (see the proxy authentication example). I'm definitely doing something wrong with authentication, but...what?
 HttpHost proxy = new HttpHost("http-proxy", 80);
    HttpHost target = new HttpHost(url, 80);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user,password));

try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(new SystemDefaultCredentialsProvider()).build()) {

RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
HttpGet httpget = new HttpGet("/basic-auth/user/passwd");
httpget.setConfig(config);

HttpResponse response = client.execute(target, httpget);
}

A: The problem seems to be that you are setting new SystemDefaultCredentialsProvider() when you are building the HTTP client. I guess you intention was to set credsProvider, to which you have just added proxy user and password.


text:
Q: Can I Stop NSViewRepresentable layout lag for NSTextView? I am using an NSTextView inside NSViewRepresentable in a SwiftUI app.
The NSViewRepresentable correctly resizes to the height of the NSTextView, so the text flows to multiple lines, but on the first render after creation it only shows a single line.
It appears that the NSTextView is rendered correctly on this first frame, with the text wrapped at the right point, but the NSViewRepresentable is not displaying the full height.
The NSTextView is created, and the text set on NSTextStorage in the makeCoordinator() method of NSViewRepresentable, i.e. before NSViewRepresentable requests the view.
I override NSTextView to set the intrinsicContentSize:
    override func layout() {
        invalidateIntrinsicContentSize()
        super.layout()
    }

    override var intrinsicContentSize: NSSize {
            layoutManager!.ensureLayout(for: textContainer!)
            return CGSize(width: -1.0,
                          height: ceil(layoutManager!.usedRect(for: textContainer!).size.height))
    }

I think this issue was hinted at by the 'bobble' mentioned in this post. The height tracking method is different but also fails to set the first frame.
Is there anything I can do to force layout sooner on the NSTextView? The view is not fixed width so it needs to flow dynamically.
Here is a minimal reproduction:
import SwiftUI

    let font = NSFont.systemFont(ofSize: 20, weight: .bold)
    let testString = "This long string demonstrates how its full extent is not shown on the first frame of an NSTextView rendered within an NSViewRepresentable."
    let fontAttribute = [NSAttributedString.Key.font: font]
    let testText = NSAttributedString(string: testString, attributes: fontAttribute)

    class InternalTextView: NSTextView
    {
        init() {
            super.init(frame: NSRect.zero)
            setContentHuggingPriority(.defaultHigh, for: .vertical)
        }

        override init(frame frameRect: NSRect, textContainer container: NSTextContainer?) {
            super.init(frame: frameRect, textContainer: container) }

        required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }

        override func layout() {
            invalidateIntrinsicContentSize()
            super.layout()
        }

        override var intrinsicContentSize: NSSize {
            layoutManager!.ensureLayout(for: textContainer!)
            return CGSize(width: -1.0,
                          height: ceil(layoutManager!.usedRect(for: textContainer!).size.height))
        }
    }

    class TextViewCoordinator: NSObject {
        private(set) var view: InternalTextView

        init(withText text: NSAttributedString) {
            view = InternalTextView()
            view.textStorage?.setAttributedString(text)
            super.init()
        }
    }

    struct TextView: NSViewRepresentable
    {
        let text: NSAttributedString

        func makeNSView(context: Context) -> NSTextView { context.coordinator.view }

        func updateNSView(_ nsView: NSTextView, context: Context) { }

        func makeCoordinator() -> TextViewCoordinator { TextViewCoordinator(withText: text) }
    }

    struct ContentView: View
    {
        let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
        @State var showText: Bool = false

        var body: some View {
            HStack {
                Spacer()
                ScrollView {
                    VStack {
                        if showText {
                            ForEach(1..<10) { _ in
                                TextView(text: testText)
                            } }

                        Spacer()
                    }.frame(maxWidth: 600)
                }
                Spacer()
            }
            .onReceive(timer) { _ in
                showText.toggle()
            }
        }
    }

Frame 1:

Frame 2:


text:
Q: Error upon opening terminal in Ubuntu in relation to pythons vitualenv Yesterday I installed pythons Virtualenv. Now every time I open a terminal I receive this error.
mkdir: cannot create directory '/home/riley/.virtualenvs': File exists
Why Is it trying to create this directory every time I open a terminal?


text:
Q: sed command - remove all commas from text between HTML tag Please, someone help. I need to find and remove commas from specific HTML tags like
 and
 in command line but only from this tags.
Example:
...

Sample header, with some, text with commas

Sample header, with some, text with commas

Loreipsum sit amet, dolor...

...

and I use:
sed "/
/,/<\/h3>/s/,//g"

but this command remove commas from all code... I need only from
 and
 tag.

A: you can try this
sed -e '/<*>/s/,/ /g' stack4.html

inside stack.html below strings are written

Sample header, with some, text

Hi, what's your namiue

Sample header, with some, text

Sample header, with some, text

hyt,ujt,yj

Sample header, with some, text

jkj
Sample header, with some, text

o/p i got

Sample header  with some  text

Hi, what's your namiue

Sample header  with some  text

Sample header  with some  text

hyt,ujt,yj

Sample header  with some  text

jkj
Sample header  with some  text

if you want to do only for h3 and h4 then below command may be help you
 sed -e '/<h[3-4]>/s/,/ /g' stack4.html

Hope it will work :)


text:
Q: How to find the 2nd largest number in the array, but return the last index that the value appears in? My actual problem is to find the number in a data set with the 2nd highest frequency. I'm initializing an array that is the size of the largest number in the data set and then incrementing the corresponding indexes in the array each time the number appears in the data set. If more than two indexes shares the 2nd highest frequency then I need to return the larger index. My code returns the correct answer in some cases, but not all and I am having trouble finding the error in my logic.
int secondFreq(int data[], int maxNum){
    int highest = 0;
    int secondHighest = 0;
    int x;

    for(x = 0; x < maxNum; x++){
        if(data[x] > data[highest]){
            secondHighest = highest;
            highest = x;
        }
        else if (data[x] > data[secondHighest]){
            secondHighest = x;
        }
        else if (data[x] == data[secondHighest]){
            secondHighest = x;
        }
    }

    return secondHighest + 1;
}

Here is an example of an array that yields the wrong answer. The left number is the index and the right number is the value stored at that index. My function returns 12 (11th index+1), but it should be returning 5 (4th index + 1).
    0 - 2
    1 - 2
    2 - 5
    3 - 2
    4 - 5
    5 - 4
    6 - 2
    7 - 2
    8 - 6
    9 - 4
    10 - 3
    11 - 6
    12 - 2
    13 - 2
    14 - 3

A: In your example, the second '6'(index 11) will go to the 'else if (data[x] > data[secondHighest])' and update the 'secondHighest' to be the same as 'highest'. This logic cannot deal with the condition where there are multiple highest value.
To fix, you can put a 'else if(data[x] == data[highest])' before other 'else if'.
However, you will get another incorrect anwser if your data set is as below:
0 - 2
1 - 2
2 - 5

I will change the code to be more clear and readable as below:
int secondFreq(int data[], int maxNum){
    int secondLargestValue = findsecondLargestValue(data);
    return findIndexofValue(data, secondLargestValue) + 1;
}

int findsecondLargestValue(int data) {
    ...
}

int findIndexofValue(int data, int value) {
    ...
}

A: Were it not for the efficiency consideration of being 2 pass, (so this is not going to be the best answer), I would want to say something like:
int secondFreq(int data[], int maxNum)
{
    double          highestVal = data[0];   // start with the first
                        // entry
    int             secondHighest = -1; // will send back 0 if everything
                    // ties for first
    int             x;      // for loop index

    for (x = 1; x < maxNum; x++) {
    if (data[x] > highestVal) {
        highestVal = data[x];
    }
    };
    for (x = 1; x < maxNum; x++) {
    if (data[x] != highestVal)
        &&((secondHighest == -1) || (data[x] >= data[secondHighest])) {
        secondHighest = x;
        }
    }

    return secondHighest + 1;
}

It is harder to mess up, though it does look through twice.

A: Your code has two problems:

*

*You will need to set highest = x; in the case of data[x] == data[highest].

*secondHighest should be initially pending.

The following is an example modification:
int secondFreq(int data[], int maxNum){
    int highest = 0;
    int secondHighest, secondFlag = 0;//secondFlag : Whether secondHighest has been determined, 0 : undetermined, 1(Not 0) : determined
    int x;

    for(x = 1; x < maxNum; x++){
        if(data[x] > data[highest]){
            secondHighest = highest;
            highest = x;
            secondFlag = 1;
        }
        else if (data[x] == data[highest]){
            highest = x;
        }
        else if (secondFlag == 0 || data[x] >= data[secondHighest]){
            secondHighest = x;
            secondFlag = 1;
        }
    }

    if(secondFlag)
        return secondHighest + 1;
    else
        return 0;//All elements same
}


text:
Q: Express app.use() is not handling routes in separate file "Cannot GET /" Result is "Cannot GET /"
Both files are in the same folder and if i use routes directly in the app.js file it works.
app.js
//ROUTING
var router = require('./index');
app.use('/*', router);
//ROUTING END

index.js
var express = require('express');
var router = new express.Router();
var user = require("./controllers/user");
var products = require("./controllers/products");
router.get("/", products.products_list);
router.get("/user/profile", user.profile);
router.get("/user/signup", user.signup_redirect);
router.get("/user/logout", user.logout_redirect);
router.post("/user/signup", user.signup_post);
router.get("/user/login",user.login_redirect);
router.post("/user/login", user.login_post);

module.exports = router


text:
Q: web.py User Authentication with PostgreSQL database example I am trying to copy and use the example 'User Authentication with PostgreSQL database' from the web.py cookbook. I can not figure out why I am getting the following errors.

*

* at /login
'ThreadedDict' object has no attribute 'login'

* at /login
'ThreadedDict' object has no attribute 'privilege'
Here is the error output to the terminal for the second error. (the first is almost identical)

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/application.py", line 239, in process
    return self.handle()
  File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/application.py", line 230, in handle
    return self._delegate(fn, self.fvars, args)
  File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/application.py", line 420, in _delegate
    return handle_class(cls)
  File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/application.py", line 396, in handle_class
    return tocall(*args)
  File "/home/erik/Dropbox/Python/Web.py/Code.py", line 44, in GET
    render = create_render(session.privilege)
  File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/session.py", line 71, in __getattr__
    return getattr(self._data, name)
AttributeError: 'ThreadedDict' object has no attribute 'privilege'

127.0.0.1:36420 - - [25/Aug/2012 01:12:38] "HTTP/1.1 GET /login" - 500 Internal Server Error

Here is my code.py file. Pretty much cut-n-paste from the cookbook. I tried putting all of the class and def on top of the main code. I have also tried launching python with sudo as mentioned in another post.

import web

class index:
    def GET(self):
        todos = db.select('todo')
        return render.index(todos)

class add:
    def POST(self):
        i = web.input()
        n = db.insert('todo', title=i.title)
        raise web.seeother('/')

def logged():
    return False  #I added this to test error #1, Now I get error #2
    #if session.login==1:
    #    return True
    #else:
    #    return False

def create_render(privilege):
    if logged():
        if privilege == 0:
            render = web.template.render('templates/reader')
        elif privilege == 1:
            render = web.template.render('templates/user')
        elif privilege == 2:
            render = web.template.render('templates/admin')
        else:
            render = web.template.render('templates/communs')
    else:
        render = web.template.render('templates/communs')
    return render

class Login:

    def GET(self):
        if logged():
            render = create_render(session.privilege)
            return '%s' % render.login_double()
        else:
            # This is where error #2 is
            render = create_render(session.privilege)
            return '%s' % render.login()

    def POST(self):
        name, passwd = web.input().name, web.input().passwd
        ident = db.select('users', where='name=$name', vars=locals())[0]
        try:
            if hashlib.sha1("sAlT754-"+passwd).hexdigest() == ident['pass']:
                session.login = 1
                session.privilege = ident['privilege']
                render = create_render(session.privilege)
                return render.login_ok()
            else:
                session.login = 0
                session.privilege = 0
                render = create_render(session.privilege)
                return render.login_error()
        except:
            session.login = 0
            session.privilege = 0
            render = create_render(session.privilege)
            return render.login_error()

class Reset:

    def GET(self):
        session.login = 0
        session.kill()
        render = create_render(session.privilege)
        return render.logout()

#web.config.debug = False

render = web.template.render('templates/', base='layout')
urls = (
    '/', 'index',
    '/add', 'add',
    '/login', 'Login',
    '/reset', 'Reset'
    )

app = web.application(urls, globals())
db = web.database(dbn='postgres', user='hdsfgsdfgsd', pw='dfgsdfgsdfg', db='postgres', host='fdfgdfgd.com')

store = web.session.DiskStore('sessions')

# Too me, it seems this is being ignored, at least the 'initializer' part
session = web.session.Session(app, store, initializer={'login': 0, 'privilege': 0})

if __name__ == "__main__": app.run()

A: Okay, I was able to figure out what I did wrong. Total newbie stuff and all part of the learning process. This code now works, well mostly. The part that I was stuck on is now working. See my comments in the code
Thanks

import web

web.config.debug = False

render = web.template.render('templates/', base='layout')
urls = (
    '/', 'index',
    '/add', 'add',
    '/login', 'Login',
    '/reset', 'Reset'
    )

app = web.application(urls, globals())
db = web.database(blah, blah, blah)

store = web.session.DiskStore('sessions')
session = web.session.Session(app, store, initializer={'login': 0, 'privilege': 0})

class index:
    def GET(self):
        todos = db.select('todo')
        return render.index(todos)

class add:
    def POST(self):
        i = web.input()
        n = db.insert('todo', title=i.title)
        raise web.seeother('/')

def logged():
    if session.get('login', False):
        return True
    else:
        return False

def create_render(privilege):
    if logged():
        if privilege == 0:
            render = web.template.render('templates/reader')
        elif privilege == 1:
            render = web.template.render('templates/user')
        elif privilege == 2:
            render = web.template.render('templates/admin')
        else:
            render = web.template.render('templates/communs')
    else:
                ## This line is key, i do not have a communs folder, thus returning an unusable object
        #render = web.template.render('templates/communs')  #Original code from example

        render = web.template.render('templates/', base='layout')
    return render

class Login:

    def GET(self):
        if logged():
                        ## Using session.get('something') instead of session.something does not blow up when it does not exit
            render = create_render(session.get('privilege'))
            return '%s' % render.login_double()
        else:
            render = create_render(session.get('privilege'))
            return '%s' % render.login()

    def POST(self):
        name, passwd = web.input().name, web.input().passwd
        ident = db.select('users', where='name=$name', vars=locals())[0]
        try:
            if hashlib.sha1("sAlT754-"+passwd).hexdigest() == ident['pass']:
                session.login = 1
                session.privilege = ident['privilege']
                render = create_render(session.get('privilege'))
                return render.login_ok()
            else:
                session.login = 0
                session.privilege = 0
                render = create_render(session.get('privilege'))
                return render.login_error()
        except:
            session.login = 0
            session.privilege = 0
            render = create_render(session.get('privilege'))
            return render.login_error()

class Reset:

    def GET(self):
        session.login = 0
        session.kill()
        render = create_render(session.get('privilege'))
        return render.logout()

if __name__ == "__main__": app.run()