text:
Q: How to Spread Plot's Date Axis According To Years When Plotting With Seaborn? I'm trying to train a Linear Regression Model with Python via using Google Stock Prices that can be found here: https://www.kaggle.com/medharawat/google-stock-price
And trying to predict future stocks by given features. After that I'm planning to plot it with the values in current dataset.
First, I read dataframes with date values with date parser and concatted these 2 dataframes into one in order to split it myself:
parser = lambda date: pd.datetime.strptime(date, '%m/%d/%Y')
df_test=pd.read_csv("/kaggle/input/google-stock-price/Google_Stock_Price_Test.csv",parse_dates=[0], date_parser=parser)
df_train=pd.read_csv("/kaggle/input/google-stock-price/Google_Stock_Price_Train.csv",parse_dates=[0], date_parser=parser)
df=pd.concat([df_train,df_test])

Then I changed the type of Close column as "float64" and plotted the Date-Close relation via using seaborn:
import seaborn as sns
sns.relplot(x='Date', y='Close', data=df,kind="line")

The output is:

I've managed the necessary column translations until this part of the code. In this part I split the data frame, create and trained model, and predicted values.
from sklearn.model_selection import train_test_split

X=df[["Open","High","Low","pc"]]
y=df["Close"]
X_train,X_test,y_train,y_test = train_test_split(X,y)

from sklearn.linear_model import LinearRegression
model=LinearRegression()
model.fit(X_train,y_train)
model.score(X_test,y_test)
y_pred=model.predict(X_test)

What I want to achieve after this part is I want to set these predictions' dates for future dates in order to combine them into my data frame and plot. I managed to create 2 data frames for real and predicted data and concat and melt them into new dataframe in order to plot it.
dates=(df[-320:]["Date"]).values
df_plot=pd.DataFrame(columns=["Date","Close"])
df_plot["Date"]=dates
df_plot["Close"]=y_test.values.transpose()

df_predd=pd.DataFrame(columns=["Predicted","Date"])
df_predd["Predicted"]=y_pred.transpose()
df_predd["Date"]=dates
df_predd["Date"]=df_predd["Date"]+pd.offsets.DateOffset(years=8) #I want to plot it as future predictions

concatenated = pd.concat([df_predd.assign(dataset='df_predd'), df_plot.assign(dataset='df_plot')],axis=0)
melted_df=pd.melt(concatenated,id_vars=["Date"],value_vars=["Predicted","Close"])

sns.relplot(x='Date', y='value', data=melted_df,hue="variable",style='variable',kind="line",height=10)

Here's the undesired output:

I want an output something like that:

What Am I Missing? I checked the Date Column's type. It's datetime. I can't spread the x-axis as the first plot shown above.
Any helps will be appreciated. Thanks in advance.

A: To simplify your example, consider these two toy dataframes:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(1)

df_actual = pd.DataFrame(data={
    "date"  : pd.date_range(start="2020-01-01", periods=8, freq="MS"),
    "value" : np.random.randint(10, 30, 8),
})

df_forecast = pd.DataFrame(data={
    "date"  : pd.date_range(start="2020-08-01", periods=4, freq="MS"),
    "value" : np.random.randint(10, 30, 4)
})

If you want to plot the actual and forecast values together on a shared x axis, the easiest way I can think of is to differentiate them by adding a type column and feeding it to the hue parameter of seaborn's lineplot.
Remember to "connect" the two lines by making the first value of the forecast dataframe the same as the last value of the actual dataframe:
#first forecast value == last actual value
df_forecast.iloc[0, :] = df_actual.iloc[-1, :]

df_forecast["type"] = "forecast"
df_actual["type"] = "actual"

df = pd.concat([df_actual, df_forecast])

Finally, you create your plot like so:
plt.figure(figsize=(10,5))
sns.lineplot(x="date", y="value", hue="type", data=df)


text:
Q: simply access members of other namespaces I am using the famous module pattern for creating namespaces however its cumbersome to write ns1.ns2.member to access a member from ns3(ns1.ns2.ns3).
I do not like using a shortcut var(_ns2=ns1.ns2) for this purpose also with statement considered harmfull so what is the better to handle this problem?
is it possible to combine scope of namespaces or whatever? thanks.
var NS1 = (function ()
{
    function $(id)
    {
        return document.getElementById(id);
    }

    return {
        $: $
    }
})();

NS1.NS2 = function()
{
    function someFunc()
    {
        // Do not want the below one.
        NS1.$('...');
        // Is there a way to access $ directly.
        // without defining a variable for it here or using with statement.
    }
}();

A: I don't really know what you're talking about, and even if I make believe I do I don't see what's so bad about "ns1.ns2.ns3", but here are a couple of ideas:
(function(tempNamespace) {
  blahBlah(tempNamespace.something, tempNamespace.somethingElse);
  // ...
})(ns1.ns2.ns3);

Or combine a few:
var nsCombined = $.extend({}, ns1, ns2, ns3); // jQuery

Some description of what it is you're doing with these namespaces and how much code we're talking about would be useful. I find that once you start using something like jQuery, for most pages — even with fairly complicated client-side behavior — the need for large long-term data structures goes way down.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Give an icon to dynamic array elements in react I have a dynamic number of arrays like [1,2,3,5,7], [1,2,3], [2,7,8] ...  where the elements represent a platform id which helps to identify platforms like PlayStation, Xbox etc. uniquely...
I want to link a react-icon to each element of the array such that each symbol gets linked to the id of the platform it represents, for eg:
if platform id of playstation is 2 i want <FaPlaystation/> icon linked to it so that i can display it in my react card component, basically something like this:

how do i implement this in react? I'm getting platform ids via a prop called plat, upon iterating it like this :
let platMain = plat.map(plat=>plat.platform.id);

i get the array of ids

A: You can create a Map (not to be confused with Array.prototype.map()) to be later used to lookup the associated icon component by the numeric key provided.
import { FaAndroid, FaAngular, FaReact, FaDev } from "react-icons/fa";

const map1 = new Map([
  [1, FaAndroid],
  [2, FaAngular],
  [3, FaReact],
  [4, FaDev]
]);

const platMain = [2, 3, 4, 5, 6, 7];

export default function App() {
  return (

Hello CodeSandbox

Start editing to see some magic happen!

      {platMain.map((key) => {
        const icon = map1.get(key);
        return icon ? icon() : null;
      })}

  );
}

Or similar with a plain old Object with numeric keys.
import { FaAndroid, FaAngular, FaReact, FaDev } from "react-icons/fa";

const map = {
  1: FaAndroid,
  2: FaAngular,
  3: FaReact,
  4: FaDev
};

const platMain = [2, 3, 4, 5, 6, 7];

export default function App() {
  return (

Hello CodeSandbox

Start editing to see some magic happen!

      {platMain.map((key) => {
        const icon = map[key];
        return icon ? icon() : null;
      })}

  );
}

A: You can do like this
// utility to get Icon
const getPlatformIcon = (platformId) => {
  switch (platformId) {
    case 1:
       return <FaIconName />
    case 2:
       return <FaPlaystation/>
    case 3:
       return <FaAnotherIconName />
    default:
       return <FaDefaultIcon /> // or return null if you don't have it
  }
}

// your component
export default function({plat}) {
  return (

      {
        plat.map(p => getPlatformIcon(p.platform.id))
      }

  )

}

A: I think this method would be better:
const yourArray = [
{id: 2, icon: <FaPlaystation /> },
{id: 4, icon: <AnotherIcon />},
{id: 6, icon: <AnotherIcon />}
]

//then

{yourArray.map((item)=>(

item.id

{item.icon}

))}


text:
Q: Finding string in file with batch and call other batch I am on a need to finde if an output log ends with a desired string, and call another batch if it does.
I have already tried some solutions at StackOverflow but it is still not working.
title Validate daily execution

findstr /C: "Exiting with code 0" .\logs\20171116.log
if %errorlevel%==0 (
BBBB
CALL  AutoLogEmail
) else (
AAAAAAAa

)

And the file that I am looking for in a sub folder, with the name above has the values

16-11-2017  6:50:00,75 START PROCESS XXXXXXX.ISPAC Microsoft (R) SQL
  Server Execute Package Utility Version 11.0.2100.60 for 64-bit
  Copyright (C) Microsoft Corporation. All rights reserved.
Started:  06:50:00 DTExec: The package execution returned
  DTSER_SUCCESS (0). Started:  06:50:00 Finished: 06:52:03 Elapsed:
  122.929 seconds 16-11-2017  6:52:04,00 END PROCESS XXXXXXXX.ISPAC : Exiting with code 0

Is there any especific function that I shall use? Can someone point me the error and explain why it is not working?
Thanks in advance
Helder

A: You could try something like this:
@echo off
title Validate daily execution

>nul find "Exiting with code 0" .\logs\20171116.log && (
    CALL  AutoLogEmail
) || (
    echo not found
    pause
)

In this case, it depends on the find command, which whill cause the && operator (which only executes the command after it if the previous one doesn't fail) to either call autologmail, or echo not found if it didn't find anything.

A: The Space between /c: and the string in your findstr command is your problem.
With that Space in the place indicated, findstr will generate a syntax-error message and set errorlevel to 2.
Remove it and findstr will attempt to find the string in the file.


text:
Q: Синтаксический анализатор (построение грамматики) ? Нужно построить синтаксический анализатор. В частности для языка создать  контекстно-зависимую грамматику( LL) Везде встречаются примеры только для чисел и знаков, у меня присутствуют только 4 буквы(A, B, C, D)  и для них надо построить грамматику .
Есть ли примеры построения грамматики ?
A: Тут не плохой пример. Грамматика это просто набор правил. Таблица синтаксического анализа лишь отражает порядок применения этих правил.


text:
Q: Time zone used for Oracle Date field TL;DR - am I correct in thinking there is no way to determine the timezone used for a given record of a Date field when the server's time zone was changed at some point in the past?
A factory control system was designed to use UTC server (not Oracle) time so all Date columns were UTC. At some point in the past they changed the server time to local. Now years later, they would like the apps to display the correct date. Without knowing the date the change occurred, is there a way to SELECT so all Date records would be correct? I think I can either make the "modern" records correct or the pre-change records correct but not both unless I know when that happened. Since it was a Windows OS change, I don't think even the alert log would help assuming they haven't trimmed it at some point, but it's not easy to get any info or server access from them anyway. It had been 10g and is now 12c.

A: Correct.  Oracle's DATE datatype is timezone agnostic.  If you want to store timezone info in the database, use TIMESTAMP WITH TIMEZONE datatype.


text:
Q: Unable to retrieve data for a specific date in SQL I'm trying to retrieve data for a specific date with query:
Select * from table_1 where activity_date = to_date('13-09-2017','DD-MM-YYYY');

But I'm not getting any result.
But when I query below:
Select * from table_1 where activity_date >= to_date('13-09-2017','DD-MM-YYYY');

I'm getting the data for days greater than equal to 13-09-2017.
Any help?

A: When you compare dates remember that you usually compare some kind of a timestamp. A timestamp usually also has hours, minutes, seconds etc. So in your database you probably have a whole timestamp like '13-09-2017' + specific hour, minutes and so on, whilst to_date explicitly only formats your DD MM and YYYY causing the hour, minutes and seconds to be equal to 0. The query is probably not returning any records as you probably don't have a date with the exact time equal to 00:00:00.
That's also why a comparison like >= will return results. Because your '13-09-2017' database entries are all greater than '13-09-2017' (with hour equal to 00:00:00) because they all have some hours, minutes and seconds to them, for e.g 13-09-2017 04:02:45 which is greater than 13-09-2017 00:00:00).
How to solve this? Well for example:
SELECT *
FROM table_1
WHERE activity_date >= to_date('13-09-2017','DD-MM-YYYY')
  AND activity_date < to_date('14-09-2017','DD-MM-YYYY')

A: It seems the data type of your column is Date Time and hence when you are querying with just date (13-09-2017), it searching for date as well as time (13-09-2017 00:00:00). Seems there are no record in your database with this exact date time stamp and hence no results are being returned. Below query will work in your case:
SELECT *
FROM table_1
WHERE activity_date >= to_date('13-09-2017','DD-MM-YYYY')
  AND activity_date < to_date('14-09-2017','DD-MM-YYYY');


text:
Q: ImageMagick adds thick horizontal lines to PNGs extracted from PDF Edit July 7, 2017: Downgrading to ImageMagick 6.9.5 solved this problem, which may be Cygwin-specific. I still don't know the underlying cause.
I need to extract data via OCR from images in PDF reports published by Chicago Public Schools. An example PDF is here (NB: this link downloads the file automatically rather than opening it in the browser). Here's a sample image (from PDF page 11, print page 8), extracted with pdfimages -png version 0.52.0 on Cygwin:

I'd like to crop each bar into its own file and extract the text with OCR. But when I try this with ImageMagick (version 7.0.4-5 Q16 x86_64 2017-01-25 according to convert -version), using the command convert chart.png -crop 320x600+0+0 bar.png, I get this image, with horizontal lines that interfere with OCR:

Running pdfimages to extract to PPM format first and then converting to PNG while cropping gives the same result, as does round-trip converting the extracted images to SVG format with ImageMagick's rsvg delegate, and fiddling with the PNG alpha channel changes the line's colors from gray to white or black but doesn't eliminate them. I've found a workaround of round-trip converting extracted images through JPG (introducing ringing artifacts, which I hope are irrelevant). But I don't see why I should have to do this. Incidentally, ImageMagick introduces the lines to PNGs even if I run a null conversion convert chart.png chart.png, which ought to leave the image unchanged:

I have found other complaints that PDF software adds horizontal lines to images, but none of them exactly matches this problem. A discussion thread mentions that versions of the PDF standard somehow differ in their treatment of alpha channels, but my knowledge of graphics is too poor understand the discussion fully; besides, my images get horizontal lines added after they're extracted from the PDF, because of something internal to ImageMagick. Can anyone shed some light on the causes of the grey lines?

A: Using the latest ImageMagick 7.0.6.0 Q16 Mac OS X, I get a good result. As mentioned above by Bonzo, the correct syntax for IM 7 is magick rather than convert. The use of convert reverts to IM 6. Also do not use magick convert either.
magick chart.png -crop 320x600+0+0 +repage bar.png

If this does not work for you, then there must have been a bug in your older version of IM 7. So you should then upgrade.
Note also the +repage is needed to remove the virtual canvas


text:
Q: Bijective local diffeomorphism is a diffeomorphism Let $X,\ Y$ be manifolds in $\mathbb R^n$ (they are locally diffeomorphic to open subsets of some euclidean space.) I have a question about this fact (an exercise in Guillemin and Pollack):

An injective local diffeomorphism $f: X\rightarrow Y$ is a
diffeomorphism onto an open subset of $Y$.

This seems too trivial to me and hence I think I musunderstand something. I would prove this claim as follows.
The map $f: X\rightarrow f(X)$ is bijective. It is differentiable at any point since it is locally smooth (and even locally diffeomorphic), and the inverse $f^{-1}: f(X)\rightarrow X$ is also differentiable at any point because given any point $f(x)\in f(X)$, the map $f$ is a diffeomorphism near $x$, so $f^{-1}$ is differentiable at $f(x)$. Thus $f$ is a global diffeomorphism. Because of this and since $X$ is open in itself, $f(X)$ is open in $Y$.
How bad/good does this proof look?


text:
Q: passing parameters from models I have this model where I upload a file and save it to s3 . Here is the model.
class ExcelFiles(models.Model):
    PLAN_CHOICES = (
        ('x1', 'x1'),
        ('x2', 'x2'),
        ('x3', 'x3')
    )
    company =models.CharField(max_length=80)
    plan_type=models.CharField(
        max_length=20,
        choices=PLAN_CHOICES,default='BASE')
    excelFile = models.FileField(blank=False, null=False, upload_to=excel_directory_path)

and here is the code for excel_diectory_path
def excel_directory_path(instance, filename):
    print("instnace", instance)
    present_date = date.today()
    #import pdb;pdb.set_trace();
    return 'company_excel_sheets/{}-{}-{}/'.format(present_date.year, present_date.month, present_date.day, filename)

What i basically wanted is to store my files company_excel_sheets/company/plan_type/time
so that no files get overwritten while saving in s3 .


text:
Q: How to stub private methods of a class under test by sinon I am trying to stub a private method in a class. I have searched in many blogs that have no right answers or not related to my concern. Can we stub private methods?
This is my code which uses the private method I want to stub:
public static async create(roleTO: RoleTO): Promise<RoleTO> {
        log.trace('Inside create method with roleTO: ', roleTO);
        roleTO.name = roleTO.name.trim();

     await this.validateIfRoleNameIsTaken(roleTO); //validateIfRoleNameIsTaken it is a private method. I am trying to stub this method

        let rolePO: RoleDocument = <RoleDocument>PoToConverter.getRoleTo2Po(roleTO);
        console.log(rolePO,'this is rolelPO');

        log.trace('Persisting Role: ', rolePO);
      rolePO = await rolePO.persist();
       console.log(rolePO._id,'tydtydytd');

        roleTO._id = rolePO._id;
        console.log(roleTO);
        return roleTO;

    }

This is the private method definition:
 private static async validateIfRoleNameIsTaken(role: RoleTO | RolePO): Promise<void> {
        log.trace(`Inside validateIfRoleNameIsTaken method with role: `, role);
        let RoleModel: RoleModel = <RoleModel>model(ROLE_MODEL);

        let existingRoles: RolePO[] = await RoleModel.findByName(role.name);

        log.debug(`Fetched following roles from storage: `, existingRoles);
        ValidationUtil.failIfMatchExists(role.name, existingRoles);
    }


text:
Q: Pandas read JSON into Excel I am trying to parse JSON data from an URL. I have fetched the data and parsed it into a dataframe. From the looks of it, I am missing a step.
Data Returns in JSON format in excel but my data frame returns two columns: entry number and JSON Text
import urllib.request
import json
import pandas
with urllib.request.urlopen("https://raw.githubusercontent.com/gavinr/usa-
mcdonalds-locations/master/mcdonalds.geojson") as url:
data = json.loads(url.read().decode())
print(data)
json_parsed = json.dumps(data)
print(json_parsed)

df=pandas.read_json(json_parsed)
writer = pandas.ExcelWriter('Mcdonaldsstorelist.xlsx')
df.to_excel(writer,'Sheet1')
writer.save()

A: I believe you can use json_normalize:
df = pd.io.json.json_normalize(data['features'])

df.head()

      geometry.coordinates geometry.type    properties.address  \
0  [-80.140924, 25.789141]         Point         1601 ALTON RD
1  [-80.218683, 25.765501]         Point        1400 SW 8TH ST
2  [-80.185108, 25.849872]         Point    8116 BISCAYNE BLVD
3   [-80.37197, 25.550894]         Point    23351 SW 112TH AVE
4   [-80.36734, 25.579132]         Point  10855 CARIBBEAN BLVD

  properties.archCard properties.city properties.driveThru  \
0                   Y     MIAMI BEACH                    Y
1                   Y           MIAMI                    Y
2                   Y           MIAMI                    Y
3                   N       HOMESTEAD                    Y
4                   Y           MIAMI                    Y

  properties.freeWifi properties.phone properties.playplace properties.state  \
0                   Y    (305)672-7055                    N               FL
1                   Y    (305)285-0974                    Y               FL
2                   Y    (305)756-0400                    N               FL
3                   Y    (305)258-7837                    N               FL
4                   Y    (305)254-3487                    Y               FL

  properties.storeNumber properties.storeType             properties.storeUrl  \
0                  14372         FREESTANDING  http://www.mcflorida.com/14372
1                   7408         FREESTANDING   http://www.mcflorida.com/7408
2                  11511         FREESTANDING  http://www.mcflorida.com/11511
3                  34014         FREESTANDING                             NaN
4                  12215         FREESTANDING  http://www.mcflorida.com/12215

  properties.zip     type
0     33139-2420  Feature
1          33135  Feature
2          33138  Feature
3          33032  Feature
4          33157  Feature

df.columns

Index(['geometry.coordinates', 'geometry.type', 'properties.address',
       'properties.archCard', 'properties.city', 'properties.driveThru',
       'properties.freeWifi', 'properties.phone', 'properties.playplace',
       'properties.state', 'properties.storeNumber', 'properties.storeType',
       'properties.storeUrl', 'properties.zip', 'type'],
      dtype='object')


text:
Q: Ignore WHERE clause only for a specific value @ValCycle = 'Selected Cycle'

select * from cycletable where case
        cycle = when @ValCycle = 'Selected Cycle' Then @NCycle
            else cycle
end

This is my query. The problem is when the value of @ValCycle is different than 'Selected Cycle' then all the null values of the column cycle are ignored. I need all of them including null, blank, and any value.
Can anyone help?

A: You've got a bit of a syntax error so your query won't run but I get the idea.
Edit: you've clarified where the values come from, and when valcycle = 'selected cycle' then use a value that was previously selected
select *
from cycletable
where
     @ValCycle <> 'Selected Cycle' OR
     cycle = @NCycle

Note that you don't say what value @ValCycle will have if a value is not selected; if it's null then <> wont work; use IS NULL instead. It's also not clear whether @NCycle will ever have a NULL value and you'll be looking for the nulls in the table; if you are, you'll need
select *
from cycletable
where
     @ValCycle <> 'Selected Cycle' OR
     (@NCycle IS NULL AND cycle IS NULL) OR
     cycle = @NCycle

You're aiming for a condition that is always true if the value of @ValCycle isn't 'Selected Cycle'. Personally I'd have skipped it and made @NCycle either null (if I wanted all rows) or a value (if I wanted those values) and had WHERE @NCycle IS NULL Or cycle = @NCycle - single variable rather than two - unless having @NCycle of NULL is a valid value that you want to search for
Consider that this form may give better plans, and is more self documenting:
IF @ValCycle = 'Selected Cycle'
  select *
  from cycletable
  where
     cycle =  @NCycle;
ELSE
  select *
  from cycletable;

Extending queries with "optional parameters" style where clauses may pick a poor plan because the plan can be cached based on one set of parameters and a new set means the plan is suboptimal. Splitting them up into separate queries avoids this, though you may still encounter issues with any parameterized queries, if the distribution of values you seek is uneven

A: Comparing NULL with NULL for equality will always be false.
I think that your issue cannot easily be solved using a CASE statement. I would convert it to the following SQL:
select * from cycletable where
  @ValCycle = 'Selected Cycle' or
  cycle = @NCycle OR (cycle IS NULL AND @NCycle IS NULL);

An OR in a WHERE-clause can be problematic for performance. Indexes will not be used in that case. To improve the query plans, you have two solutions:

*

*Conversion to an IF...ELSE statement is already proposed in Caius Jard's answer. You only need to add the correct NULL checks to the WHERE-clause of the query in the IF-block. But that would introduce another OR, so the IF-block needs to be rearranged and extended:

IF @ValCycle <> 'Selected Cycle' OR @ValCycle IS NULL --I'm not sure if @ValCycle can be NULL...
  select *
  from cycletable;
ELSE IF @NCycle IS NULL
  select *
  from cycletable
  where cycle IS NULL;
ELSE
  select *
  from cycletable
  where cycle = @NCycle;

*Using UNION:

select * from cycletable where @ValCycle = 'Selected Cycle'
UNION
select * from cycletable where cycle = @NCycle
UNION
select * from cycletable where cycle IS NULL AND @NCycle IS NULL;


text:
Q: NSTimer expires when the device is locked My application supports the GPS and it runs both in foreground and background. I have started a timer , which is working perfectly unless the device is locked.
I want the timer to keep on running even when the device is locked.
Can anyone tell me how this can be done ?

A: Whichever way you start a timer, the default run mode is like below:
     Timer *timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(run) userInfo:nil repeats:YES];

     [[ NSRunLoop currentRunLoop ] addTimer:timer forMode:NSDefaultRunLoopMode ];

using NSDefaultRunLoopMode. You want more flexibility, so change forMode to take NSRunLoopCommonModes instead and you should be fine.


text:
Q: Cannot download proper file from google server to my server I am trying to download a file from google server to my server. But the file downloaded is corrupted. While googling I found that the responce is a raw file. I followed the coding listed below:
$getUrl = 'https://www.googleapis.com/drive/v2/files/' . $file_id.'?alt=media';
    $authHeader = 'Authorization: Bearer ' . $oAuthToken;

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $getUrl);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);

        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            $authHeader
        ]);

        $data = curl_exec($ch);
        $error = curl_error($ch);

        curl_close($ch);

$file = $_SERVER['CONTEXT_DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'invoice'.DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.'user_' . $user_id .DIRECTORY_SEPARATOR.'receipts'.DIRECTORY_SEPARATOR. $file_name;

    file_put_contents($file ,// where to save file
$data);

The Output which I am getting in data is:
Data Loaded: HTTP/1.1 200 OK

X-GUploader-UploadID: AEnB2Upo0zPUHctSPxMvqYuBkIwhKUEWIGHQdbhsDAqbfdy_a6-0LW1L1OqZ4xFtu3OyZiSJOAoRWr2wcbV5LTyELTPK8GcI-g

Content-Type: image/jpeg

Content-Disposition: attachment

ETag: "pvTNHKA6KkAgXTpZXMwU4P67ELo/NDg5OTU3NzE5"

Vary: Origin

Vary: X-Origin

Expires: Tue, 03 Nov 2015 10:00:12 GMT

Date: Tue, 03 Nov 2015 10:00:12 GMT

Cache-Control: private, max-age=0, must-revalidate

Content-Length: 36410

X-Goog-Hash: crc32c=vzEAxg==

Server: UploadServer

Alternate-Protocol: 443:quic,p=1

Alt-Svc: quic=":443"; p="1"; ma=604800

����JFIF��C    !"$"$��C����"��
���}!1AQa"q2���#B��R��$3br�
%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz���������������������������������������������������������������������������
���w!1AQaq"2�B����   #3R�br�
$4�%�&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������?�f���J���rd��4yF@5���Wm�    ����Gfw�\��]N�s�ןiW��]F�t2k��Rg�J���]�*9���\k��n����ֺk��9�>P�؝ͩ@jϻ��*�y�������:UӋl�J�$M�֍���ԭ��g�(x�ur�Q�lն�*jڶk.��]��VsGu)_BW5
ϊYX�N��51՝�7!xy<U�Nj�1ަx���j�BL]�+�ë2W;��U���������dWCit�kG�k?J�984�P��g��/��;X{��@*��7��'�\u�k6K�/�������\(�5Bk���'Pԕs�~��]j�y���u�N�xvξ�TP��*u�ޮ/�BWo�����.sY}`��iw�Ei[HN+�ҧ,�&�+)tS�s��Sj.V� ��6�V8a]Qw8�7����Em�a��n��<W-�C�Ċ$�T��%�Ur�zVI����%�b�W#$8�����W����Fŝ9K0⺭&,Y5���i�g�+nT�   �rf��eG�Gҟah02+C�
:TXW�Sn�L  n*��g�5�U��&�[䊎E�rG\⡛n��6$d���X�73Z��6�����+sY4m�=H�y���H3��k��g�9�B�R��ڳs�Щ�:MCPTBs�ư��7?Z�/�K�_��M��F �k>{�Nd;�\�؟5���O�չ�<�/���
t�JgE ���4��}i3L.��L�`����)ƚzQa\a
��*&�E��m�L9��ZcQ`�Êa=��j2iX@M4�z?:����He�ʽ��x����0V��������篭��
�/��<
�����f��    ��Z2�Vm�S]A�����T4l�th��sS���r�8AA�4V�x����   S�<U    F�+
��ʢZ��ha�J
4U��=�d5vӖ�QJ�d�?5] Z����4��-aiQ�a]~�k�(�y��#����)Yf�=:f$sYKg��l�+ƨ��F��4u'�kKp�s�`(5��@�v�馮s՝�����Ҩ\�`��b���H��[H��*�3�Hpy�Bc�ڦ�O,�O;��N���T�$�Q�4�!r櫙�Ԋ��
��Z�0������u��Y0�rj����U�(��(�#��;�NMUb��~5�e����^9��}��H-�Z�>>��2�ƺ�9���=��'ף���k��'���x���Ү7�Y�~2���n}�'3��ot{Uψ�/����L�#]�    >��⩦m���Z~��w;���Z�g|0���%�`N�JI���]R"1�.�h5�)Hθc�wq\oSh�06lܖ��r8�j�_�6vr�l�c�C��Y�!��$
%��
 T��~&�l'$zΗ�؛�n.���N�^k��o��-c���9�q��*~��f�����c�L��[��n|.���}.�   m���[�ڶ�Q#��rZ�PZ�ۜ�z�]��;-�A<���ǿu˽R�M��-g�c�c����N�~��TI�6�&mr�������݅vG��    �-Q�5�a�r�'��s�BG#ھ.��5�&��u�P�$�<�v��ǜc�һ-�w�4�{u�|Cv�|a��F۞rO<���qQl�Xi${��b��u�'ֺM7R��-���_��   R� :>a�,Tp�)��*�=�k�.�$���ZM�
�i�`q�U
*�2oٲ}��cғZ� qK2zT�09�HE$;��k6�R��ҽ=qY��բyH����S̀i̸ZϽ|)����:�Ҩ#5�k�c
�[z�����[��9�+$]5vak����_8=�MR�n<�S\���k���=-${ܜU�Kp{Ukzձ�
q"�j���׷����S[0�t�H��jRA�N��6���
��j�y��)��Fi�Cb�L,zkJU��&Fi��aLy�(�.XcM$b�M4�}h��
c0�K�0����  Y�D�Q�{��\.=��[ޣf�3B�)4��TE�3y��w'�4�U}��,��cL�y�{Z��!��o9�h�3�����gD�d���<�X���k&��#J�eNW�? �ʄ����ˑ��V�qY�c��Y�}F3�uM���=
D
H��Q���6͇�T��S��`j�Г��q�&�� �
��Q��}@q�yX�zh�e�a�f�[Æ�Q�d�Kx�l�fۑ�h����@��Mp�F�1��[}�q^�Y+�e}έ_���.$܄U;{��G5d&�]�H�LʾH�w�\�#Eu7Q$�?�DA$k9S�7�W��Kw�ٞk��������סxfE�$�\ꟼzs��

��Nk�KV�\ES�+��]�i#Δ\��_l]�نz�t�%nA�b�  +���"����W5J����SQ��I4DŽd�U�AS��5���9-�!N3��%S���I�!�q0d����[Kp,m��dU��r@����[+I|��Y���;��-X\���y�r���R��1X�ۖ%��)���*��]J��NtW;#$���+��Z]5��yP�c�?J�e�->'�L�L�U���k�SM��Զ�%դN�S���t���z���\��������&��b3[�Lz`�cY�kfS��2����|�W*á�3R2%�7;p�jƛ*���ǔ������WV�O��R��zjI�
�dsv�l�V�'�.{�R鄽�����=�җW�]�É�;�MR�.���k����+�ZJ�;V�Ҏ=�Ȅga��Jl2E-��36�c��T ���@N7��-��M,k�x���r��V�\���u��}/F�"�]�3*/<��u��V���3i�(����1��5�#w=k���,�Yq��GZ�;���^4�iN�y`��k��#�FsT��T}���bq�Q�@y�[rSp�p��k���a1�������ƥ��uQ�]qϨ5���;��>����Q��yuoi#�[����������}@c�O��KUʝ���iJ۽��۞�j?��]ߣ�
��l���h�R�ڧ�jÞEr����p�.v���j$n��5��%�5lk�������d�V#<W%Z���T�2/��� KY1��d�6
�Rmݝ|�Z��+cIpePMs�\V����u9�5�eb$���Z�P
t�P�@Z�<?p��We�����jy���/d$��j�5[S���c�B�"�5��К�uZg"���2O�f���'�fIty�����ޣi��e=��Uy/��h�-3i�3Q�������#z}E.`��5���
a�ޮ|�Zi�>���X�
�����X���
ߩ��f���r=k�Y�Hn���Vm5�����X��ސ���� ��z�ǭd��I��z9����ǭ9f��.��t3���
�0�T��WK���4��)�`�X�k�g�3�
g�rk9A�b�^'�ζ��<RE�.j�ث���C+M��?�;4�0isY�
�*�إ��I?�k�H�]DD�*E<[H?�Ӗ�֊D�OJ��5��_w�����
uC8�pb�s�
Y��]n
3]f��^q�N�GZ촽@,c&��J���&���U�2"f�.5@�5�$�����qU�;�+�0   ��Nq ��v��&��Qsһ"�r�$ts��Ŀ���V��������/Ӟ��.���9��5I�b��^����;V�gf����.�k���g�F�G�Cv�A�Uu�M"���8�O�������in   �Vn��ƒoSS���bMc]L��k�\* �Ysko4�Y��un� E+�wHx5N��A��I&B�z˾��k��w�f���쒤��Q�q�֬�M�AN��#`��]x�D��\��ڴ�KK    � nL�Q'�d���>�;
B,�7K�3�rQ��U8���բ�����6��8�����KY�u&��f����r��qZZE�EY,��ч��qSZ�mn  \:}᚟T�^M2Y��Ğ|N����Y6����H�]��m�5h���M��Z��1`?{�u�����%哈�cꧡ�R;�Z�[A�ݵޖ�e��}m�,����ٔ�������w]΀�֮x[Y�`l/ʉ�s�G�Fa�T��LSm�H�n2{��KMj1si���G���:�UEs+2[�wE��mRM "<��?�\|����8=�+��uV5�x�t=W��P��j*�s��`�~��uY��wwG7�Gp�He��܎ⷬ�On��gB���:V_�2��a�L\qZZa��Hm��c��z����4U����J/�s\�pK�A*�ڽB�̝6����~^j�5/����^yRj{��/y-�+��wC���+YIa�i�Σ��W�+�-�Ɠ[���C�]�x��1�:���   _�͉�*ѷS��X��S�Z�;�����@>�Ԑ�L�5�j�*C�3R3�>Y��A�*�mT09j�Ψ�p⢗VRϟƸ��F��j:�
y�OTԌ��sU./�S��_
y&���ؿ�$P�Y&bI8���V���R�~ͱ<gc�{�-4X�]A�CښmW=)�;�m���Jp�#�teA�SM�U(���n�3B����!��dVƛy�q����g:��\��P�.��U�ڲd7jϽ� �շ1��s#Z�;�k����k��~k
�I��#��-���K�Vf�
�4~��+�-ң7'֠�Z��|���ZH��>��v�Y�wsM�=��)A&�}i
�����4�=is1�#O�w��h���SF��h�"4�����c=k7�i��ppF���y�ֳ��ZP��J�D_��
*�}j��nsE�pF�\�֞nk01�Gz|ĸ^L��$9���p��.[���tr�J!�
�S�9X��i�)+V���L��)�f�`�m��/�}+l��ҝ��k0�eᢏ�����ֺpSڑ�{Wb���Q��h���g�2�q�WM&�Jh)�C�vs��XakJ���#��P�� *=�%MH��q&�@��h&`�X�(
Srýe�Tn��7e��sT$��Ȫjs��C.4,C�6mX�pk�ҵ`���$�t52^ʝ�Q�ݞ���1�����$���.����n9j��b7�;�Ĝ�;t��ɨ��w�٨�̞Msʇ6�L1�$S�n��rB�ִ�APGj��Eh�箭es�A9�Y�E�[\jw/�Xp���f��V�ܰ���b� �����7��/���fA�����I'��¹�s���会@O͍�'�&�   �UIpv�
�4�Dy�R�GԖ1ߏ���Ұz+����G�K�_i���q2@F3\�Y����!(�"v�}��U��;���x�3_J����N�a%��]J�w:%k\"��7��\[��чc�WM����g�_�a��o�?α/$F�4�MJ�7ј�0��+[E�{NKi@(�b`{����J��8���E�-؏���1Щ=+���M^�u=2_'Q��S�ök��fmuV~��a�Rh:��W�$n<�<x��ky�n�¢M�uZV��'��Kr!�'�Tq��T��5�yY��D�u��ڲ|\ʳ��m�INA��V
v�&gC}
�\������B��+�e$����/q ����[�:u�����J6A��ݜWp�����w�jȶ���`�G=3�5]�B/sJY-�iT7?2��ԚU�a��.y�����D����Q�����m�}���0O��"��$
�hѰ��� ��^q�����)X���������h��X`zZ圂c�&    ��o-Z�i8e�Z۱�b@�����W6�H�v�a���9���f ���h9�t�MhB:������:�\E3DĂ��9��87QU5�9��O��vaj��Y��xoiu�9E
��ԩ��j��GjxU�����D��z�Q�juQҝ�ͅ��S�޴�) r1r��R٥Ȥ$Q���C��wt��3I�G#�ԟ8�RdR�Q��1g�z7�g����M*�r����Cڨʒ1<���������jX�T巓Һ�CP�d�v��li\��g��zWi&�aQ01�)�2�8�������c]�i*GJ��b�FW1Ř[
!���k�m%GjE�ҎFR�����G���5��d/����_AG#9�y
�i|��5�d/�E�v���8�%�(?����#����@����9!zR����Vt��)�K���F9CzS7�5�3ڗ�,z
\�.rau��[��Nt���t�?�R�d�Nu��U�q[#M���z��tQO���g!=�X��W��ڦK/j9Y) ��R����`v�~�=)r��Ndk_��u�����٩~����3������Tmg���������/l����ߣR�p�p�k��_9��G�`v���R�m�q{��N��{`�t�׸�
k�W �����D��?�?l/`���k�R�md���̟�4�h��Ən/`���hz�m���2�x��?�i�a{w_�@�� �pB�O�wڥ���س�Me7sҦ:��^z���k_B���9�8��{F��p�SI��oun�Ǫ�=�j��Oq�nw�'���֤���np�>ƭh*m5�  q^Cz�},U�D:9G��=:�>ic0�ԆY��ڼUhݠ�$��QG&��`�θ��_%�%J��I�܅��_�̇��u��Gu��A/�B+/����D-�/o�Z�2� �P�K���������rt�f�هr�E>��������T��������b+���s}�`  "U?\�*߆.���6,�ljc��4J�QF�A~ ��-���r�����$[�)c<2.~�֭��w�MŤ��]�����b���ɪI�#d9�V�ib\�+�6�t��2Xܜ��'ѻ��d��5��N����Q���QG?vU��:խ\�����89��&�:�Լ�MAA;�������-��x(��=>���%-�Ywc������A:�I�?�MekY��d�\$hÞ@j�m�:[�����_UoOqT<+����7�1�&�<B�ڬ~A�{��h���^����qă=���o9>e9�E]�N$@INj���c��_��'�d�G5�X���ի!,P eTmo]��Po:܀��;#��3�d���jZ��n�$o���;{֔�V0�`7qY�
��v7v�d9�nGU>���%��9{���ᣐ�֢�t\|�K�s�l���B������\H����S��nϙ�a�&�=ob?�N�dޯ=M`��4㬜�֞�&�G~o#�����<�����h��?ޣ�D~͝������?�+���ޥ��i{D͝�O��7����s��/������D^͝��S������kG?x�Ƶ�ѧ�r3�  ��G���p�[?ޣ�l�~�i��    ��R��ָQ���N��?ߣ�!����Qރ*z��F��ߧ
p����΃����}E8H���n��Ү����>h�����1ښ΂�������s?�O� �θ�P�\x�y��K���M(�+;��J1\��?���{�����C�;�F��q�������w��J�|��'aHYk����n���M8���/�!)�\��{o�)�?ۢ�VuOJPSҹo�������]������x�\��1�B��oޓh:PWҝ�q\��|}�K��?�F���nZpq��W�S
Y}EV�X�W������������Ԭ�c��H�����ҹ�a�N�R"����"lC���[X�Jc���,
Ei�j��jc�+�q��ar�� 8�#�x�-�J��v�e>Uvh�]�
��b��zU�`qҷ!�J�� t���w"�k��������3����e�Ȧ1�q�S�#�GҜ�O�E��ڷk�~�W�����Jbz��t��YH��]���[v�@6�3&�<Rm�X��Pw8E��3�U��$�B@�����u°��3�'�Y\���!�O#��Xrs��4O�7H���q�I!
k��i�8�H9���
l���Ƕ�"�X���)�c��i2֛8����dVNJ���{�rDaI�b)?�.H�$�����?N�;���vW�����wG�G~q���5D��6�6��X�������,��!��f�oC�*����1�����m�>�lS�����g?��)���j
��ԕ�-�NA,�}
i�G�Ġ��`�U+�!Tc�������
�'�����J$Z�(ڇp �=
v��g�+��y����$�����9�L�֖�n۵I�;��+���#7J�{k7��pج��&I�q��z,�1�[TcҪg�wsZ8�V<���㔪�{�3g#�#rƽ]������rKt�p�}ޟ�j��amNa�Z[o4Yy�[F(N0GB>��o3���)5V��&C*�Y�m��=M6��mĶ�v�RF>j�>�P�����|����qDZ�z�#���$'��U��A#����y��剁�����Y��^�r�.�<$��뛊�68���;X��I��إ�4)}
wQ�H��(����/jpb�
'���
z� ��!���)�^���i7���K�k�N���4�}�Q�����͎���M�k�?��ئ���O�^����CG�7����N>�4��ΎA{c�0��I���k�:/��؟�S�a���2�C������SN���.F?l�+˗
&�}
v�Eܦ���9X{dq�%��ģ������e1�o�(�a�Q��_zBe����q��ci��X~�'+��zMҏZ��I�d�m��iY����n�ޓ|��Н/�i?����|�07��I�Oz�?��٦ɦ>�-F��q�M��=MjO��ڨMlW��I2=��ӄ��M�d�vU����M/�$�5$v�*Ahqҗ1/�����>����6�ҙ�n:S�'?���i�r��4�!�jb&���3J��ƭ����5B����3)�F��?��?j���3�Y��~�}*���F`ո����Cn4�uƙ�J]�G�L��i��V����bgr?+j�vqV��)�
ѭ2��U�Z�(��H���՝pؠ�Kt5��Q�P&Xr3X�2s���]X�n�+Ϭ�GM-�ef��t:m�Y�ڱ�T���P�x��>Z�Ѧ����i������4��V��h� ���z�qOHqڭ�Dz��$7b�hWSgh�e �!�C![�ֽ�����)�EtB��Z��>�u�Yx�����Es�NVb�q�~��c�����j)en  �Ey%��ݏ��q�1�-�s��9�Q��5�0�T��QD2�d8?#p~��߲�9�E'kRkY\d��ո�m�q�����.*�ϔ��Vm�-��'|5iZ��H#�Uh"i�x����3��I�m�����{T�ڻ:`Z۹Ҽ��8"�t�"B���;T9�h�em���Ho������C�Բc���ʶWh<c�i:|���R*;)Ӱ�>��a�#�u�C$jHǥe�"ƥW�<ոC�N2�Ÿ\ڒUlv��b�R

Currently the file which is saving inside receipts folder is corrupted.
I tried to write the raw file in the way listed below as well, but again the file is corrupted:
$file = $_SERVER['CONTEXT_DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'invoice'.DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.'user_' . $user_id .DIRECTORY_SEPARATOR.'receipts'.DIRECTORY_SEPARATOR. $file_name;

$destination = $file;
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file);

Please help where I am making a mistake ??


text:
Q: bash reading multiple text file and setting variables how can read each lines and then set each string as separate variables.
for example:
555 = a
abc = b
5343/abc = c
22 = d
2323 = e
233/2344 = f

test1.txt
555 abc 5343/abc
444 cde 343/ccc

test2.txt
22 2323 233/2344
112 223 13/12

echo $a $d $f
desired output:
555 22 233/2344
444 112 13/12

Following script will set each line as variable but i would strings in each line as variable.
paste test1.txt test2.txt | while IFS="$(printf '\t')" read -r f1 f2
do
  printf 'codesonar %s %s\n' "$f1 $f2"

done

A: You have to use the variables you want in your read.
$: paste test1.txt test2.txt |
> while read a b c d e f g h i j k l m n o p q etc
> do echo $a $d $f
> done
555 22 233/2344
444 112 13/12

Am I missing something?


text:
Q: What is the best approach to database abstraction layer for Angular? What is the best approach to database abstraction layer for Angular, similar to something like a Content Provider in Android ?

A: Many developers build an interface to define the entity data and a set of Angular services that handle the data retrieval. If you are interested in using a declarative, stream-based architectural style, then you define the RxJS streams in those services.
Here is an example:
product.ts
/* Defines the product entity */
export interface Product {
  id: number;
  productName: string;
  productCode?: string;
  description?: string;
  price?: number;
  categoryId?: number;
  category?: string;
  quantityInStock?: number;
  searchKey?: string[];
  supplierIds?: number[];
}

product.service.ts
@Injectable({
  providedIn: 'root'
})
export class ProductService {
  private productsUrl = 'api/products';

  // All products
  products$ = this.http.get<Product[]>(this.productsUrl)
    .pipe(
      tap(data => console.log('Products', JSON.stringify(data))),
      catchError(this.handleError)
    );
}


text:
Q: Stored Procedure using IF I need some help, I am somewhat still new to SQL. I have a stored procedure that is executed from another application as a smartobject. My code before te changes look like the code in Section 1. I changed the code as per Section 2 so that the stored procedure would first look if the Sales id type was in fact 3 comparing with the membershipnumber in the table memberships from the stored procedure and then do the same in the members table. If the query was 3 with the membership number I wanted it to use the expiry date in the members table and not the section
SELECT @ExpiryDate = DATEADD(YEAR, 1, DATEADD(d, -1, DATEADD(m, 0, @CreatedDate)))
That woudl add 364 days to current date
Section1
USE [HotelStayWorkflow]
GO
/****** Object:  StoredProcedure [dbo].[CP_Create_Card]    Script Date: 3/7/2017 2:50:06 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[CP_Create_Card]
    -- Add the parameters for the stored procedure here
 @membershipNumber VARCHAR(MAX),
 @CardId BIGINT = NULL OUTPUT,
 @minsToFirstDeadline int = 2880,--defailt 2 days
 @minsToSecondDeadline int = 5760 --default 4 days

AS
BEGIN
    DECLARE @CreatedDate DATETIME = GETDATE()
    DECLARE @ExpiryDate DATETIME
    DECLARE @FirstDeadine DATETIME
    DECLARE @SecondDeadline DATETIME

    BEGIN
                SELECT @ExpiryDate = DATEADD(YEAR, 1, DATEADD(d, -1, DATEADD(m, 0, @CreatedDate)))
    END

    SELECT @FirstDeadine = DATEADD(MINUTE,@minsToFirstDeadline,GETDATE())
    SELECT @SecondDeadline = DATEADD(MINUTE,@minsToSecondDeadline,GETDATE())
    --Create Card Linked to Membership below
    IF EXISTS(SELECT * FROM Cards WHERE MembershipNumber = @membershipNumber AND Enabled = 1)
    BEGIN
        UPDATE Cards SET Enabled = 0 WHERE MembershipNumber = @membershipNumber AND Enabled = 1
    END

    INSERT INTO Cards (CardStatusId, MembershipNumber, PrintedDate, Created, Modified, ExpiryDate,FirstDeadline,SecondDeadline, Enabled)
    VALUES(1, @membershipNumber, @CreatedDate, @CreatedDate, @CreatedDate, @ExpiryDate,@FirstDeadine,@SecondDeadline, 1)
    SET @CardId = SCOPE_IDENTITY()

            -- Return Card Id

END

Section 2
USE [HotelStayWorkflow]
GO
/****** Object:  StoredProcedure [dbo].[CP_Create_Card]    Script Date: 3/7/2017 1:08:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[CP_Create_Card]
    -- Add the parameters for the stored procedure here
 @membershipNumber VARCHAR(MAX),
 @CardId BIGINT = NULL OUTPUT,
 @minsToFirstDeadline int = 2880,--defailt 2 days
 @minsToSecondDeadline int = 5760 --default 4 days

AS
BEGIN
    DECLARE @CreatedDate DATETIME = GETDATE()
    DECLARE @ExpiryDate DATETIME
    DECLARE @FirstDeadine DATETIME
    DECLARE @SecondDeadline DATETIME

    BEGIN
            IF EXIST (FROM Memberships WHERE MembershipNumber = @MembershipNumber AND SalesTypeId = 3 AND Enabled =1)
            AND
            IF EXIST (FROM Members WHERE MembershipNumber = @MembershipNumber AND Enabled =1)
            SELECT @ExpiryDate = dbo.Members.MembershipExpiry
        OR

            SELECT @ExpiryDate = DATEADD(YEAR, 1, DATEADD(d, -1, DATEADD(m, 0, @CreatedDate)))
    END

    SELECT @FirstDeadine = DATEADD(MINUTE,@minsToFirstDeadline,GETDATE())
    SELECT @SecondDeadline = DATEADD(MINUTE,@minsToSecondDeadline,GETDATE())
    --Create Card Linked to Membership below
    IF EXISTS(SELECT * FROM Cards WHERE MembershipNumber = @membershipNumber AND Enabled = 1)
    BEGIN
        UPDATE Cards SET Enabled = 0 WHERE MembershipNumber = @membershipNumber AND Enabled = 1
    END

    INSERT INTO Cards (CardStatusId, MembershipNumber, PrintedDate, Created, Modified, ExpiryDate,FirstDeadline,SecondDeadline, Enabled)
    VALUES(1, @membershipNumber, @CreatedDate, @CreatedDate, @CreatedDate, @ExpiryDate,@FirstDeadine,@SecondDeadline, 1)
    SET @CardId = SCOPE_IDENTITY()

            -- Return Card Id

END

A: Please try this, as you have not included all columns it is difficult to complete this answer.
   SELECT @ExpiryDate = M.MembershipExpiry From Memberships M WHERE M.MembershipNumber = @MembershipNumber AND M.SalesTypeId = 3 AND M.[Enabled] =1

        IF @ExpiryDate IS NULL
        BEGIN
           SELECT @ExpiryDate = DATEADD(YEAR, 1, DATEADD(d, -1, DATEADD(m, 0, @CreatedDate)))
        end

A: changed code to
BEGIN
    SELECT @ExpiryDate = MembershipExpiry From Members M WHERE M.MembershipNumber = @MembershipNumber
    Memberships MS WHERE M.MembershipNumber = @MembershipNumber AND SalesTypeId = 3 AND MS.[Enabled] =1
    IF @ExpiryDate IS NULL
            SELECT @ExpiryDate = DATEADD(YEAR, 1, DATEADD(d, -1, DATEADD(m, 0, @CreatedDate)))
END


text:
Q: Proof that there exist constants $a_i$ such that $\int_0^1 f(x)e^xdx=\sum_{i=1}^na_if(i)$ for polynomial $f(x)$ of degree less than $n$ How do I show that for positive integer $n$ and $f(x)$ all real polynomial functions of degree less than $n$ there exist constants $a_i$ such that $$\int_0^1 f(x)e^xdx=\sum_{i=1}^na_if(i)?$$
I thought maybe I can do something with the basis $(1,x,x^2,...,x^{n-1})$ of the vector space of polynomials, but I'm not sure what exactly?
Edit: $a_i$ have to be chosen independently of $f$

A: Really, this isn't about integrals. The mapping $f \mapsto \int_0^1 f(x)e^x \, dx$ is a linear functional on the $n$-dimensional space $V$ of polynomials of degree $< n$. The problem asks you to prove that in the dual space $V^{*}$, this functional is in the span of the functionals $$\phi_1 \colon f \mapsto f(1), \quad \phi_2 \colon f \mapsto f(2),\dots, \quad  \phi_n \colon f \mapsto f(n).$$
Letting this span be $X \subseteq V^{*}$, it will be enough to prove that $X = V^{*}$. If we had $X \ne V^{*}$, then there would be some nonzero $f \in X^{\bot},$ that is, we'd have $f(1) = f(2) = \dots f(n) = 0$. But this is impossible, since a nonzero polynomial of degree $< n$ cannot have $n$ distinct roots.

A: A beautifull result establishes that if $F_1,...,F_r, F$ are functionals such that $\bigcap_{i=1}^r\mathrm{Ker}(F_i)\subseteq\mathrm{Ker}(F)$, then there are numbers $a_1,...,a_r$ such that $F=a_1F_1+...+a_rF_r$. The proof can be found here
Let $V=\{\mbox{polynomials with degree }\le n-1\}$, and set $F_i:V\to\mathbb{R}$ given by $F_i(f)=f(i)$, $i\in\{1,...,n\}$. There are $n$ functionals and, by the Identity Theroem, $\bigcap_{i=1}^r\mathrm{Ker}(F_i)=\{0\}\subseteq\mathrm{Ker}(F)$, where $F:V\to\mathrm{R}$ is the functional $F(f)=\int_0^1f(x)e^xdx$.
Thus, there are reals $a_1,...,a_n$ such that $F(f)=a_1F_1(f)+...+a_nF_n(f)$ for all $f\in V$, yielding the desired result.

A: Posing:
$$f(x)=\sum_{j=0}^{n-1}c_jx^j$$
we have:
$$\int_0^1 f(x)e^xdx=\int_0^1 \sum_{j=0}^{n-1}c_jx^je^xdx=\sum_{j=0}^{n-1}c_j\int_0^1 x^je^xdx$$
$$\sum_{i=1}^na_if(i)=\sum_{i=1}^na_i\sum_{j=0}^{n-1}c_ji^j=\sum_{j=0}^{n-1}c_j\sum_{i=1}^na_ii^j$$
So, for $0\leq j\leq n-1$:
$$\sum_{i=1}^na_ii^j=\int_0^1 x^je^xdx$$
This is a system of $n$ equations in the $n$ variables $a_i$:
$$MA=q$$
The rows of $M$ are linearly independent, so the system has but one solution.


text:
Q: First letter of every word gets capitalized after saving to mysql using SQLAlchemy I am trying to using Flask+SQLAlchemy to build a rest api. I am new to this. I just encounter a wired problem. First letter of every word get capitalized after the words saved to the mysql. The code is below:
@app.route('/gifs')
def crawlHome():
    url = "http://domain.com.cn"
    newgif = Gif(url)
    db.session.add(newgif)
    db.session.commit()

class Gif(db.Model):
    __tablename__ = "gifs"
    uid = db.Column(db.Integer, primary_key = True)
    url = db.Column(db.String(200))
    def __init__(self, url):
        self.url = url.title()
    @property
    def serialize(self):
        return {
            'uid' : self.uid,
            'url' : self.url
        }

And the saved url is like this: "Http://Domain.Com.Cn". Why? I am very new to python. So, please forgive my ignorance.

A: Your url is capitalized because you are using the title function from the string built-in type.
>>> "http://domain.com.cn".title()
'Http://Domain.Com.Cn'

You need to replace self.url = url.title() by self.url = url in the Gif model __init__ function.


text:
Q: Is it okay to submit an update that is almost different from the first release? This is an iOS app for the Apple App Store I wanna know if it is okay to submit an update to an app that is different from the first release. For example, my first release would be a game, but on my next release, I want to remove the game but instead make a couple of web views and table views, etc. Will Apple stop me from updating the app?
The Mailbox is one example. When I first downloaded it, it doesn't really do anything but countdown on the number of people getting the app. Honestly, I lost patience and didn't bother trying it out. But I don't think it's an entirely different app, just that the countdown was a layer on top of a fully functioning Mailbox app, correct?

A: Every time you update new version, apple review team will review your new ipa, so what have updated write in new version.
So if your new updated app is valid means follow all guidelines than there is no problem.


text:
Q: Macro to format y- axis in Excel I've written some code to create a second y-axis in a chart. I recorded a macro when I formated the second y-axis and the code looks great. However, it doesn't work when I try to run it from the VBA code..
I've tried the Format Painter (the first y-axis), which would be optimal if it worked, and also by formating the second y-axis "by hand"
This is what I have (and it's doesn't work..)
Formating the second y-axis to Calibri ("by hand"):
ActiveChart.Axes(xlValue, xlSecondary).Select
Selection.Format.TextFrame2.TextRange.Font.Name = "+mj-lt"      'This line doesn't work...
Selection.Format.TextFrame2.TextRange.Font.Size = 14
Error code: Method TextFrame2 of Object 'ChartFormat' failed
Using Format Painter:
ActiveChart.Axes(xlValue).Select
Selection.Format.PickUp    'This line doesn't work...
ActiveChart.Axes(xlValue, xlSecondary).Select

Error code: Object doesn't support this property or method.
Does anyone know why none of the methods work or if there's a work around?

A: I found a work around by using:
With ActiveChart.Axes(xlValue, xlSecondary).TickLabels.Font
   .Name = "Calibri"
   .Size = 16
End with

I haven't been able to solve the issue with Format Painter though...


text:
Q: Event being declared as Delegate While going through C# example codes, I have found this declaration:
public event myEventHandler myEvent = delegate { };

What does this statement mean? It is not inline with other declarations of delegate I have seen on internet.

A: public event myEventHandler myEvent = delegate { };

Assigns an function to the event when an instance of the class is created by simply delegating it with anonymous function.
When assigning a function to event's invocation list, the following notation is used
myClass.myEvent += delegate { };

However the following assignment is also valid inside the parent class, but it basically discards all the existing invocation list unless it is used in ctor.
myEvent = delegate {};


text:
Q: Page numbering style I want to use a "roman" page numbering in tableofcontents, listoffigures, listoftables and in the chapter called "simboli" and, then, restart the page numbering with "arabic" style in the following chapters.
I've used the following code
\begin{document}
\pagestyle{scrheadings}
\input{cap/title}
\newpage
\pagenumbering{Roman}
\tableofcontents
\newpage
\listoffigures
\newpage
\listoftables
\newpage
\input{cap/Simboli}
\setcounter{table}{0}
\setcounter{equation}{0}
\setcounter{figure}{0}
\pagenumbering{arabic}
\input{cap/01}

The restult is that tableofcontents, listoffigures, listoftables are correctly numbered but the chapter "simboli" uses "arabic" numeration. A side-effect is that the first page of "cap/01" is the number "3" (but I can fix it).
Thanks.

A: Here's a suggested solution. The main idea is to insert \newpage -- \clearpage will work as well -- before \pagenumbering{arabic}.
\documentclass{scrreprt}
\pagestyle{scrheadings}
% ... remainder of preamble
\begin{document}
\pagenumbering{Roman}
\input{cap/title}
\newpage
\tableofcontents
\newpage
\listoffigures
\newpage
\listoftables
\newpage
\input{cap/Simboli}

\newpage % <- this is new
\setcounter{table}{0}
\setcounter{equation}{0}
\setcounter{figure}{0}
\pagenumbering{arabic}
\input{cap/01}
% ... remainder of document
\end{document}


text:
Q: Symfony2 and form theming/customization (required/help/errors) Maybe I'm overlooking something, and hopefully this is done very easy.
I have a form and what I want in the end is the following result:
Fields which:

*

*are mandatory/required

*have an error currently

*have help

should get an extra a-Tag after the label and an extra div, filled with the help and/or the error, if applicable.
What I got to work is, that required fields get the a-Tag by using this:
{% use 'form_div_layout.html.twig' with field_label as base_field_label %}

{% block field_label %}
    {{ block('base_field_label') }}

    {% if required %}

    {% endif %}
{% endblock %}

So, what I tried already were different versions of this:
{% use 'form_div_layout.html.twig' with field_label as base_field_label %}

{% block field_label %}
    {{ block('base_field_label') }}

    {% if required or help is defined %}

    {% endif %}
{% endblock %}

{% block field_row %}
    {% spaceless %}

            {% if required or help is defined %}

                    {{ form_errors(form) }}
                    {{ help }}

            {% endif %}

            {{ form_label(form) }}
            {{ form_widget(form, { 'attr': {'class': 'grid_4'} }) }}

    {% endspaceless %}
{% endblock field_row %}

And I can't get this to work.
So my questions are:

*

*Where do I get the help text from, which can also contain HTML? I tried this within the form builder without success - but at least with an exception:
$builder    ->add('subject', 'text', array(
    'label' => 'Subject',
    'help' => 'Can be formatted content with HTML-Elements',
    ));

*How can I tell that the current field has an error (to add a class to the row) and if so also display it? {{ form_errors(form) }} did not output anything, no matter where I place it within `field_row˚.

A: There is no help text, you have to create Form Extension for field and add it to default options.
Example in SF 2.1 Beta 1:
namespace Webility\Bundle\WebilityBundle\Form\Extension;

use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormViewInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class HelpFormTypeExtension extends AbstractTypeExtension
{

    public function buildView(FormViewInterface $view, FormInterface $form, array $options){
        $view->setVar('help', $options['help']);
    }

    public function getExtendedType(){
        return 'field';
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
            'help' => null
        ));
    }
}

And register it as a service:
<service id="webility.form.extension.help" class="Webility\Bundle\WebilityBundle\Form\Extension\HelpFormTypeExtension">
        <tag name="form.type_extension" alias="field" />
</service>

For the errors question:
Do you have any errors to print? Check that in controller if validation fails:
echo '
'; print_r( $form->getErrorsAsString() ); echo '
'; exit;

A: To solve it as stated in my question Maciej Pyszyński's anwser was very helpful.
I solved it in this case in another way, which I also want to post here. According to the manual "Adding "help" messages" I build this:
Note This solution won't work together with the formbuilder and needs some tweaking in twig.
To get the help ''-tags (actually they are divs now) …
{% block field_label %}
    {{ block('base_field_label') }}

    {% if attr.class is defined and '_hint' == attr.class %}

            Help Icon

                {% if help is defined %}
                    {{ help|raw }}
                {% else %}
                    Somebody forgot to insert the help message
                {% endif %}

    {% endif %}
{% endblock %}

To get the right class on an error
{% block field_row %}
    {% spaceless %}

            {{ form_label(form) }}
            {{ form_widget(form, { 'attr': {'class': 'grid_4'} }) }}

    {% endspaceless %}
{% endblock field_row %}

And the call from the template

    {{ form_label(form.field, null, { 'attr': {'class': '_hint'}, 'help': 'Help text or variable containing it' }) }}
    {{ form_widget(form.field, { 'attr': {'class': 'grid_4'} }) }}


text:
Q: Is it memory leak, or limitation on function calls, or what? I am writing a C program that uses lots of recursive functions. I am also using a dynamic list to store some data while recursing. I implemented a Push function to push data into the list.
After several calls for the push function " > 17,000 times" i am getting the following error:
Unhandled exception at 0x77963c47 in Prob - Cap CE.exe: 0xC00000FD: Stack overflow.
at return HeapAlloc(_crtheap, 0, size ? size : 1); that is called from stack->listNode = malloc(sizeof(struct Node)); in the Push function.
I opened task manager and identified that I still have lots of free memory. So I guess it is not a memory leak issue.
Is there any limitation on how much I can add to the list, or how many times I can call a function?

A: The size of the stack allocated for a process is fixed. So even if the system has plenty of memory, you can overflow the stack.
What's more, your process itself usually has plenty of memory. It's just the stack that's quite small.

A: ">17,000 times" is not "several". It's bloody loads.
You can't expect your stack to hold 17,000 frames (and how much it can hold is implementation-dependent, and also depends on how much data is in each frame).
Use iteration instead.

A: Well, there will be limitations, for instance recursion can only go as far as the stack memory allocated for your app. Since you're getting a stack overflow, this seems like it is probably the problem.
See Change stack size for a C++ application in Linux during compilation with GNU compiler for some details on how to modify the stack size. If you can't get it to work right even with a huge stack, then it's likely you'll have to do some optimizations to reduce the amount of memory you're using, or to limit your recursions.
You could try moving some of your stack variables into the heap by allocating them rather than just doing local declarations, just as a first idea. If you could post some code as to what your recursive functions look like, we might be able to give suggestions. A likely solution to your ills is just to convert your functions from using recursion to using loops.


text:
Q: Get all onedrives from c# I am looking for a c# snippet for getting all OneDrive's. There is a lot of sample for PowerShell, but I am looking for c# snippet that can provide all OneDrives in a tenant.

A: OneDrive's are simply specialized/personalized site collections in SharePoint that were created from the SPSPERS template.  To find all OneDrives you can use Brian Jackett's technique for enumerating site collections with CSOM, just add an additional filter to only get sites based on the SPSPERS template using the SPOSitePropertiesEnumerableFilter.Template property.
Here is a sample (this is nearly identical to Mr. Jackett's, with the addition of the line sspFilter.Template = "SPSPERS") :
List <SiteProperties> list = new List <SiteProperties>();

SPOSitePropertiesEnumerable ssp = null;
SPOSitePropertiesEnumerableFilter sspFilter = new SPOSitePropertiesEnumerableFilter();
SharePointOnlineCredentials creds = new SharePointOnlineCredentials("myUsernameGoesHere", securePassword);

using (ClientContext cc = new ClientContext("myURLGoesHere"))
{
    cc.Credentials = creds;

    String nextIndex = null;
    Tenant tenant = new Tenant(cc);

    //loop through all site collections including personal sites
    //borrowed this code from after decompiling SPO Management Shell assemblies
    sspFilter.IncludePersonalSite = PersonalSiteFilter.Include;
    sspFilter.IncludeDetail = true;
    sspFilter.Template = "SPSPERS";

    do
    {
        sspFilter.StartIndex = nextIndex;
        ssp = tenant.GetSitePropertiesFromSharePointByFilters(sspFilter);

        cc.Load(ssp);
        cc.ExecuteQuery();

        list.AddRange(ssp);
        nextIndex = ssp.NextStartIndexFromSharePoint;
    }while(nextIndex != null);

    foreach (SiteProperties sp in list)
    {
        //DO YOUR WORK HERE FOR EACH SITE COLLECTION, such as looping through subwebs
        // OR Logging to a file, or determining user ownership, etc.
        cc.Load(cc.Web, w => w.NoCrawl,
                                    w => w.Webs,
                                    w => w.Url);
        cc.ExecuteQuery();

        //check subweb(s)
        foreach (var subweb in cc.Web.Webs)
        {
            cc.Load(subweb, sw => sw.NoCrawl,
                                        sw => sw.Url);
            cc.ExecuteQuery();
        }
    }
}


text:
Q: Best approach to make a fullscreen WPF app I'm creating a full-screen application in WPF and i need to choose how to actually resize the contents to use all the available space on the screen.
As far as i know, there are 2 solutions:

*

*Grids with stars-dimensions

*ViewBox wrapper

I think they both do the job but depending on the application one is better than the other: when should the grid approach be used? And when the viewbox method is acceptable?

A: A Grid is always going to give you more flexibility than a ViewBox, what if you want some components of your application to have fixed heights / widths? For example the panels at the side of visual studio do not change in size as the application window size changes.

A: I'd do some experimentation:
I agree with ColineE and karam:
Create a Grid using Stars for columnwidths and rows to help layout the program.
Then wrap the specific items you need to scale in viewboxes.
So, I guess this answer is 1/2 combined.
Check this sample code to see what I mean...
<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

<TextBlock Grid.Column ="0"  Text="Left"/>

    <Viewbox Grid.Column ="1" >
        <TextBlock  Text="Right"/>
    </Viewbox>
</Grid>

A: You cannot zoom with Grids and star dimensions. ViewBox can scale its content.


text:
Q: Exclude items from sortable I have below sample table code,

    Title

        Row 1

        Row 2

        Row 3

        Row 4

        Row 5

I'm applying below jQuery Sortable, which works fine,
$("#Table1 tbody").sortable({
});

But, now I want to exclude sortable for "tr" having class "disabled", to do I'm applying below code (the jquery selector), but it DOESN't work. Is there anything wrong with selector? I have to use "thead" and "tbody" in HTML table.
Or is there any alternative approach? Thanks,
$("#Table1 tbody tr:not(.disabled)").sortable({
});

A: Use the items option:

Specify which items are eligible to sort by passing a jQuery selector
  into the items option. Items excluded from this option are not
  sortable, nor are they valid targets for sortable items.

$("#Table1 tbody").sortable({
    items: 'tr:not(.disabled)'
});

Demo

A: you can Use items option to specifiy which items inside the element should be sortable.  Like:
$("#Table1 tbody").sortable({
    items: ':not(.disabled)'
});

Click here for more references:


text:
Q: Forward declarations cause errors after code refactor My original class structure was similar to:
//def.h
namespace A
{
   struct X {};
}

and forward declarations where needed:
//file that needs forward declarations
namespace A { struct X; }

After some refactoring, X was moved to a different namespace, but to keep old code "working" using directives were used:
//def.h
namespace B
{
   struct X {};
}
namespace A
{
   using ::B::X;
}

Now we can access the same class keeping the old syntax A::X, but the forward declarations cause errors. The second problem is that the error message I'm getting doesn't point to where the forward declarations are, and finding/replacing the forward declarations is time-consuming.
For now I fixed the problem (the hard way).
What is the best approach to deal with this situation?
IMO, the using shouldn't be there at all, and all code that uses X should be refactored to accomodate the new namespace (this is one solution), but unfortunately this isn't an option.
The actual code is a lot more complicated, this is a simplified example.

A: I realize this is more about new code than about refactoring existing code, but I like using a special header called X_fwd.hpp for such cases.
// X_def.hpp
namespace B
{
   struct X {};
}
namespace A
{
   // NOT: using namespace B; // does not participate in ADL!
   typedef ::B::X X;  // OR: using ::B::X;
}

// X_fwd.hpp
namespace A { struct X; }

// some file needing declaration of X
#include <X_fwd.hpp>

This makes it a lot easier to find forward declarations, and also to change them after the fact, because the change is isolated in one place only (DRY...).
NOTE1: AFAIK, there is no technical difference between using Peter Wood's answer of a typedef and your using declaration. Note that a using directive using namespace B; could cause trouble because these are ignored by Argument-Dependent-Lookup. Even worse, some of your code might then even silently call the wrong function overload because you are not pulling in the new namespace B anymore!
NOTE2: In the comments to the question, an Ideone example was given. This nicely illustrates a subtlety about name lookup inside namespaces: to quote from the draft Standard, section 3.4.3.2 Namespace members [namespace.qual], clause 2

For a namespace X and name m, the namespace-qualified lookup set S(X,
  m) is defined as follows: Let S'(X, m) be the set of all declarations
  of m in X and the inline namespace set of X (7.3.1). If S'(X, m) is
  not empty, S(X, m) is S'(X, m); otherwise, S(X, m) is the union of
  S(Ni, m) for all namespaces Ni nominated by using-directives in X and
  its inline namespace set.

This explains the following tricky ambiguity
namespace A
{
    struct X1{};
    struct X2{};
}

namespace B
{
    using A::X1;    // OK: lookup-set is both namespace A and B, and a single unique name is found (at this point!)
    struct X1;      // OK: lookup-set is namespace B, and a single unique name is found

    struct X2;      // OK: lookup-set is namespace B, and a single unique name is found
    using A::X2;    // error: lookup-set is both namespace A and B, and no unique name is found (at this point!)
}

So the validity of having both a direct declaration and a using-declaration with the same name inside a namespace is order-dependent. Hence the convenience of a single declaration in a fwd header file.

A: The best approach is to fix the code.
You can do it in two steps :

*

*fix all forward declares

*remove using ::B::X;


text:
Q: Pass prompt values in advance while running a python script There is a python script already created by other team member, while running the script it asks for some prompts for example user and password. As initially it was created assuming that every one will manually run the script by supplying prompt values.
Now I am trying to automatically run the script using CRON job, but I am not sure how to pass the prompt values in advance while running the script.
Here is a simple prompt present in the script
pwd = getpass.getpass(prompt="Enter your password for user {}:
 ".format(user))

Thanks

A: I assume, want the to enter the values like python main.py value1 value2 value3 into the command line. If so then you can use the sys module of python. In your python script add the following code
import sys
val1 = sys.argv[1]
val2 = sys.argv[2]
val3 = sys.argv[3]

Here sys.argv is a list with all elements typed after python in the command line.
Its 0th element is the script name i.e. main.py in this case. Other elements are corresponding arguments you have passed like value1, value2 etc.
You can schedule a CRON job to type the command in command line with username and password as cmdline arguments

A: you can do something like: echo my_password | python the_python_script.py
if you need many input : { echo input1; echo input2; } | python the_python_script.py
but you should edit the script as others have suggested


text:
Q: Getting exception "PhpOffice \ PhpSpreadsheet \ Reader \ Exception" when parsing specific csv file Something in a csv file I am trying to import using Maatwebsite's Laravel Excel package (which uses PhpOffice's PhpSpreadsheet package) is causing the import to blow up with the following exception:
PhpOffice \ PhpSpreadsheet \ Reader \ Exception
C:\Users\jasona\AppData\Local\Temp\laravel-excel-mbAxJfb8Hm5yF5BKNzhJ0MZmmMzAHQnR is an Invalid Spreadsheet file

I believe there is some data in the file causing this to blow up as if I reduce the number of records in the file down to a few, it works just fine.  Problem is, I do not know what I am looking for as the root cause of this.  Has anyone else run into this issue?  What am I looking for?

A: Switching the file format from csv to xlsx resolved this issue.  I tried changing the delimeter to a pipe symbol, but that didn't make a difference.
Not sure what bad data was in there.


text:
Q: Can I create a multi-color cell without a gradient in Excel? I want to apply two colors to one cell and separate them diagonally. I know that there is a function to add gradients in Excel, but I haven't found a way to set the strength of the color stop.

A: So after playing around a little bit, I figured out how to do it. My mistake was that I only added two color stops, when I should've added 4 color stops, in order to remove the color gradient. The gradient is being automatically added to create a smooth color transition between two colors. If you make the color stop distance between two colors as small as possible, you won't see a color gradient.
Here is my code:
With Selection.Interior
    .Pattern = xlPatternLinearGradient
    .Gradient.Degree = 225
    .Gradient.ColorStops.Clear
End With

With Selection.Interior.Gradient.ColorStops.Add(0)
    .Color = RGB(255, 0, 0)
    .TintAndShade = 0
End With

With Selection.Interior.Gradient.ColorStops.Add(0.49999999)
    .Color = RGB(255, 0, 0)
    .TintAndShade = 0
End With

With Selection.Interior.Gradient.ColorStops.Add(0.5)
    .Color = RGB(0, 255, 0)
    .TintAndShade = 0
End With

With Selection.Interior.Gradient.ColorStops.Add(1)
    .Color = RGB(0, 255, 0)
    .TintAndShade = 0
End With

And here is how it looks like: Two colored Excel cell

A: Create an image in Photoshop or similar, resize and insert into cell.


text:
Q: psycopg2 rowcount for UPDATE is non-zero even without UPDATE changes Following the documentation of rowcount, I should be able to get how many rows were updated with a UPDATE query e.g.
>>> cur = conn.cursor()
>>> cur.execute(
    'UPDATE users SET current_session_active=%(current_session_active)s WHERE users.id = %(id_1)s AND users.app = %(app_1)s',
     {'current_session_active': False, 'id_1': '884492906', 'app_1': 'Telegram'}
)
>>> cur.rowcount
1

I understand cur.rowcount = 1 as "the row you selected had the field current_session_active set to True, and now you updated it to False". I get confused when I repeat the query and I get the same value for cur.rowcount
>>> cur = conn.cursor()
>>> cur.execute(
    'UPDATE users SET current_session_active=%(current_session_active)s WHERE users.id = %(id_1)s AND users.app = %(app_1)s',
     {'current_session_active': False, 'id_1': '884492906', 'app_1': 'Telegram'}
)
>>> cur.rowcount
1
>>> cur.execute(
    'UPDATE users SET current_session_active=%(current_session_active)s WHERE users.id = %(id_1)s AND users.app = %(app_1)s',
     {'current_session_active': False, 'id_1': '884492906', 'app_1': 'Telegram'}
)
>>> cur.rowcount
1

Being the two UPDATE identical, I would expect the second one to have cur.rowcount = 0, since the data already got updated the first time and there is nothing to be updated the second time. Why do I get cur.rowcount = 1 the second (and the n-th) time?

A: As mentioned in the comments by @Cavin Dsouza, to get cur.rowcount = 1 only when the row value is modified you need to add a field in the WHERE clause to filter out rows that would not be updated.
>>> cur = conn.cursor()
>>> cur.execute(
    'UPDATE users SET current_session_active=%(current_session_active)s WHERE users.current_section_active = TRUE AND users.id = %(id_1)s AND users.app = %(app_1)s',
     {'current_session_active': False, 'id_1': '884492906', 'app_1': 'Telegram'}
)
>>> cur.rowcount
1
>>> cur.execute(
    'UPDATE users SET current_session_active=%(current_session_active)s WHERE users.current_section_active = TRUE AND users.id = %(id_1)s AND users.app = %(app_1)s',
     {'current_session_active': False, 'id_1': '884492906', 'app_1': 'Telegram'}
)
>>> cur.rowcount
0


text:
Q: batch file command to powershell command I have a following batch(.bat file) command which is working great. However, i need to convert it into powershell command and need to run it through powershell. I have went through different ways that i have found online but none of them seems to work the way i want it to.
Batch command:
java -jar xyz.jar -url https://xyz.abc.com -user xyz123 -passwordHash abchgfqwfjhd1232bfyevt7676 -clientId GFGFhjxgsVGGF -clientSecret GFhjdhjdhdGGGbfsilwueibJGBjg -input C:\abc\Newfolder\xyz\  -v >> %logfile%

Till now i have just been able to run this basic powershell command. can someone please assist?
Powershell command:
Start-Process -FilePath https://xyz.abc.com

A: Maybe this helps:
 $logFile = "C:\temp\logFile.txt"
 Invoke-Expression "java -jar xyz.jar -url https://xyz.abc.com -user xyz123 -passwordHash abchgfqwfjhd1232bfyevt7676 -clientId GFGFhjxgsVGGF -clientSecret GFhjdhjdhdGGGbfsilwueibJGBjg -input C:\abc\Newfolder\xyz\  -v " | Out-File $logFile

Invoke-Expression docu, be aware that Invoke-Expression should only be used if the string you're invoking is under your control. Another alternative is the & (call-operator), check this stackoverflow answer, which explains the differences between them.
Hope that helps.


text:
Q: Font doesn't get loaded through webpack Hello dear webpack community.
I desperately try to load fonts using the file-loader
I tried both of these rules:
{ test: /\.(woff|eot|svg|otf|ttf)$/i, loader: `file-loader`, options: {name:'fonts/[name].[ext]'}},
{ test: /\.(woff|eot|svg|otf|ttf)$/i, loader: `file-loader?name=fonts/[name].[ext]`},

however, unfortunately, the fonts don't get pulled when asked for them in the @font-face rule:
@font-face {
    font-family: 'Example';
    font-style: normal;
    font-weight: 400;
    src: url('../fonts/Example.ttf') format('truetype');
}

This is how my project structure looks like:

This is the Webpack output:

While fonts.less is loaded, I don't see any font getting loaded through the definition of src().
Thank you a lot for any hint in advance!
See the full config file here: https://gist.github.com/MartinMuzatko/2873b52fed204bd6e8aaaa94527e34a9

A: The problem is that you're using raw-loader to transform the output of the less-loader to JavaScript so that extract-text-webpack-plugin can use it.
{
    test: /\.less$/, use: ExtractTextPlugin.extract(
        [
            {loader:'raw'},
            {loader:'less'}
        ]
    ),
}

The less-loader simply transforms the Less syntax to regular CSS. The url() won't be touched. The css-loader on the other hand treats them as imports that webpack will resolve. Only then your rules for the fonts will take effect. All you need to do is change your .less rule to use css-loader instead of raw-loader:
{
    test: /\.less$/, use: ExtractTextPlugin.extract(
        [
            {loader:'css'},
            {loader:'less'}
        ]
    ),
}


text:
Q: Add "Delete with reason" button/dialog to existing moderator tools for flagged answers While this is an old problem, it's one that will only increase with time.  As Stack Exchange sites gain in popularity, more and more users are coming to the sites in search of answers to their specific problems.
Unfortunately, not all of them understand the basic operating principals behind Stack Exchange, and ask questions, or start discussions as separate answers.
Deleting these answers is fine, but more often (I would argue almost always) than not, a new user doesn't understand why.
Granted, comments are a way of doing this, but there are drawbacks to comments:

*

*They require extra, replicated effort on the part of the moderator for something that they do repetitively

*The message will be inconsistent; messages like this would be consistent, cite the relevant resources that guide the user in the right direction

*The larger size would have a higher chance of grabbing the user's attention, as well as put more weight behind the action (as it's officially attached to the answer in a consistent manner).

*The banner will serve as an example of what not to do to other users who can see the deleted post.

Additionally, there are tools that can help with auto-commenting on posts, but these have their drawbacks as well:

*

*Not all moderators use these tools

*The messages that are delivered by the tools are ultimately generated initially by the moderators, so the message will not be consistent

*These tools are not always available on other devices (e.g., mobile platforms)

It would be helpful to the user if they had a reason indicating why the answer was deleted.  Something along the lines of:

In order to accomplish this, I propose an additional (not a replacement) button in the moderation tools labeled "delete with reason".  Mods would still be able to delete answers outright, they just have the option now of stating why in an easy manner which will allows for more time to moderate harder.
Placement is not important (screen real estate is valuable, yes), but I envision it looking something like this in the moderator tools:

When clicking "delete with reason", a dialog, much like the "close" dialog will appear with options:

Initial options for the reasons could be:

*

*Asking a new question

*Starting discussion

A mechanism like this has the potential for other benefits as well:

*

*Users with an answer deleted with a reason might actually be directed to perform the right action now, and in the future (creating better site denizens)

*Users who wish to contest the deletion of an answer on meta can cite that specific reason, which mods can specifically address (which actually might reduce noise on meta about "why was my answer deleted?")

*Can reduce flags on answers asking "why was this deleted?" (admitted, I've not personally experienced this to be a pervading problem on Stack Overflow, but this might be the case for other mods on other Stack Exchange sites)

*Other Stack Exchange sites which don't have that many users will give a better experience to their users when their first action isn't ideal for a Stack Exchange site; this will enhance the chance that the site will retain the user and get good contributions from them (as per Farseeker's comments: first, second).

Additionally, if this works well for the moderator tools, I imagine that it would not be such a leap to eventually have this graduated to users with the rep to cast delete votes, thus allowing non-mods to deliver a more clear message to new users about how to best participate on a Stack Exchange site.

A: When I have time, I follow this work-flow when handling just the sorts of not-an-answer flags on Server Fault this feature would help with.

*

*See the NA flag.

*The excerpt reads like someone who is attempting to use us as a discussion forum or some other tangential thing.

*Click on the answer to expand it.

*Add a comment with roughly the same text every time (no Greasemonkey script for me, I moderate from too many devices)

*Delete

*Go back to the mod screen to wash, rinse, repeat.

If instead of a post-flag, an auto-filled comment were to be put in there instead, it would help a lot. Since mod-comments do show up in the user's universal inbox even after a post is deleted, this would be visible to the person who matters. That would change my work-flow to:

*

*See the NA flag.

*The excerpt reads like someone who is attempting to use us as a discussion forum or some other tangential thing.

*Click the Delete-with-reason button.

*Select stock answer.

*Move on to the next flag in the queue.

Shorter and with fewer page-reloads. It is a very good idea to keep a no-reason delete around since that's still a large part of what I end up clicking.
From gut, I guess about 1 in 4 flags on Server Fault are of the type I'd used this feature on. There are a lot of technical sites out there that grow The One True $Thingy Thread style threads that gather, "but what about my weird edge case?" questions. They're damned hard to sort through when you're googling, and are exactly what Stack Exchange is trying to get away from.
When handling these sometimes I dearly wish for a Convert to a Question button since once in a (great) while the 'answer' is a darned good question. Since that isn't going to happen, some stock text I can throw in an auto-comment to point them in the right direction will make my work-flow a lot more efficient.


text:
Q: automatic way for determining ARIMA(p,d,q) - Matlab I would like to ask you if there is any automated method for calculating the order of ARIMA(p,d,q) model for any type of a time series data, in MATLAB.
This will make the forecasting model more accurate and will also save me some time. I would appreciate if anybody could help me.

A: I'm not sure if that's what you are looking for, but maybe this post on Matlab File Exchange?
http://www.mathworks.com/matlabcentral/fileexchange/25611-arfima-simulations


text:
Q: agent.add not working while console.log is I am using the Dialogflow Inline editor to make a call to an API. When I use console.log to log some of the data from the API it works. However, when I use agent.add with the same variable it gives an error.
I read some other stackoverflows about this issue where people used a promise and resolve call. I have tried to implement this in my code. However, I'm not sure if I've used it in the right way.
This is my code:
'use strict';
const axios = require('axios');

const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));

  function welcome(agent) {
    agent.add(`Welcome to my agent!`);
  }

  function fallback(agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
  }

  function randomHandler(agent){
    const regio = agent.parameters.regio;
    if (regio != "Alkmaar" && regio != "Schiphol"){
      agent.add(`Deze regio bestaat helaas niet binnen NH nieuws, kies een andere regio of kies voor het nieuws uit heel Noord-Holland`);
    } else {
        return axios.get(`https://api.datamuse.com/words?rel_rhy=book`)
    .then((result) => {

      result.data.map (res => {
        const dataArray = ""; // An array with the results. However we got it
        const words = dataArray.map( entry => entry.word );  // Get just the "word" field from each entry in the dataArray
        const wordsString = words.join(', ');   // Put commas in between each word
        agent.add( `The results are: ${wordsString}`);
      });
      });
    }
  }

  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);
  intentMap.set('random', randomHandler);
  agent.handleRequest(intentMap);
});

and this is my package.json:
{
  "name": "dialogflowFirebaseFulfillment",
  "description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
  "version": "0.0.1",
  "private": true,
  "license": "Apache Version 2.0",
  "author": "Google Inc.",
  "engines": {
    "node": "10"
  },
  "scripts": {
    "start": "firebase serve --only functions:dialogflowFirebaseFulfillment",
    "deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment"
  },
  "dependencies": {
    "actions-on-google": "^2.2.0",
    "firebase-admin": "^5.13.1",
    "firebase-functions": "^2.0.2",
    "dialogflow": "^0.6.0",
    "dialogflow-fulfillment": "^0.5.0",
    "axios" : "0.20.0"
  }
}

A: As you suspected - the problem is with Promises.
rhymingWordHandler() has an asynchronous operation in it (the web call using axios), but you're not returning a Promise.
Fortunately, axios.get() does return a Promise. You can tell because you're calling .then() on what is returned, and .then() also returns a Promise and so forth. I like to this of this as a "Promise-chain". Changing this to return a Promise is relatively simple:
return axios.get(`https://api.datamuse.com/words?rel_rhy=${word}`)
  .then( /* and so forth */ )

However, this isn't quite enough with your code. You don't need to create a Promise inside the .then() function, and doing so only confuses things.
Remember that Intent names are case sensitive - you need to use the exact same capitalization in both the name that you have in the UI as well as the name you use for intentMap.set(). You currently have "Rhymingword" in one place and "RhymingWord" in the other (one W is capitalized, the other isn't).
You also may have a minor problem that you may not be able to call agent.add(rhyme) multiple times. Some agents can only handle one or two text responses. Instead, you'll need to build the response string from the array of results.
How to build a string like this depends on your exact content. The easiest (although not grammatically correct) is to just put commas in between them. I often do them in steps, so it might look like this:
  const dataArray = // An array with the results. However we got it
  const words = dataArray.map( entry => entry.word );  // Get just the "word" field from each entry in the dataArray
  const wordsString = words.join(', ');   // Put commas in between each word
  agent.add( `The results are: ${wordsString}`. );

There are lots of problems with this, and a good solution would handle cases such as:

*

*What if there are no results?

*Should you use a different phrase before the list when there is just one word?

*What if there are two results?

*You should apply correct grammar/punctuation rules for three or more results.

But this should be a start to making sure you call agent.add() just once.

A: Solved, the problem was that I called the agent.add more than 2 times (which is the maximum). This code works for me:

const { conversation } = require('@assistant/conversation');
const functions = require('firebase-functions');
const axios = require('axios').default;
const app = conversation();

var titels = [];

axios.get(`YOUR-API`)
  .then((result)=> {
    titels.push(result.data.categories[0].news[0].title);
    /* result.data.map(wordObj => {
      titels.push(wordObj.categories.news.title);
    });*/
  });

app.handle('rhymeHandler', conv => {
  console.log(titels[0]);
  conv.add(titels[0]);
});

exports.ActionsOnGoogleFulfillment = functions.https.onRequest(app);

/* for (i = 1; i < 4; i++) {
  conv.add(words[i]);
  } */
  //console.log(words);


text:
Q: C# A way to implement a GUI roster Datatable with duplicate Column names? I am trying to create a rostering program and require several columns (28 in total), with each Day containing 4 columns (for instance |Monday| (On|Off|Duty|Hours) ).However I am running into some problems with duplicate column names I am also thinking weather it would be worth possibly splitting the tables into Days to alleviate this problem But feel this may affect future features (where I am comparing Cells day by days) Below is a picture of a completed table that I am attempting to replicate:

Do you think I am going about this the wrong way? or would it be possible to replicate this in a GUI ?
I am fairly new in the world of C# so apologies if this is something really simple!
Also apologies if this Question is slightly open to discussion.

A: The text you can see in column headers (HeaderText property) does not have to be the name of the column (Name property).
Thus a simple way to do what you want is to have Names be DayOfWeek_On/Off/Duty/Hours for example: Monday_On but have HeaderTExt be just On/Off/Duty/Hours.


text:
Q: Вывод даты и времени python3 Как форматировать дату и время для вывода в консоль.
Мне нужно вывести дату и время которое сейчас и -1 день от этого времени
date = datetime.datetime.today()
print('now ', date)

Но выводит 2017-12-07 19:52:32.297026
Как убрать миллисекунды и вывести время которое было 24ч назад
Нашел, что можно как то так
date, date.day - 1

но этот способ не сработал

A:
Как убрать миллисекунды

Чтобы получить строку без миллисекунд, просто не указывайте их в желаемом выходном формате:
>>> import datetime as DT
>>> now = DT.datetime.now(DT.timezone.utc).astimezone()
>>> time_format = "%Y-%m-%d %H:%M:%S"
>>> f"{now:{time_format}}"
'2018-04-11 16:21:50'

Вариант с str(now.replace(microsecond=0, tzinfo=None)) гарантированно тот же результат здесь даёт. DateTime in ISO 8601 + TimeZone and without microseconds. Если вам только напечатать без микросекунд нужно, то предпочтительней явно формат задать, не меняя значение самого времени.

Как ... вывести время которое было 24ч назад

>>> h24ago = (now.astimezone(DT.timezone.utc) - DT.timedelta(hours=24)).astimezone()
>>> f"{h24ago:{time_format}}"
'2018-04-10 16:21:50'

astimezone() вызовы нужны, чтобы работало в районе переходов с зимнего на летнее время (и подобное). Подробнее: Как к нынешней дате добавить 30 минут?

A: попробуй так..
import datetime
date = datetime.datetime.today()
print('now ', date)
print('day ago ', date - datetime.timedelta(1))

# форматируем вывод
# https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
print('now ', date.strftime("%A %d %B %Y"))

A: date = datetime.datetime.today()
newdata = date - datetime.timedelta(1)
print(newdata.strftime('%Y-%m-%d %H.%M.%S')


text:
Q: How to generate specific combination of numbers in Python what I'm trying to do is a function for which you give a number and it lists every string of that length that contain numbers in ascending order with the conditions that I cannot have more than 4 time the same number and my number have to be consecutive. If possible, I would like not to list numbers that are anacycle of those already listed.
For example:
fct(5) gives me
"11112
11122
11123
11223 (11222 is omitted)
11233
11234
12223
12234
12345"
Do you think it is better to do this with regex and generate every combination or to increment the numbers in a list while I browse my initial list and modify it ?
Are other languages better to do something like this ?
EDIT : Sorry I think it wasn't enough clear.
I tried at beginning to do something like :
ls = list("1111222233334")
i = -1
while ls[0] == "1":
    print("".join(ls))
    if int(ls[i]) == int(ls[i-1]) and int(ls[i]) < 9:
        ls[i] = str(int(ls[i])+1)
    else:
        i -= 1

Of course this doesn't work and I think there is too much condition if I go this way, this is why I ask if there is something already done in Python that can list every ascending number of specific length.
We cannot go over 9 so this function does anything if called with 37.
By anacycle I mean something that gives something else if read starting by the end (like "roma" and "amor").
Is it better to generate a list of every number of that length and then delete all those that do not correspond, + delete those that are equivalent to those that are already in ?

A: I finally decided to do this :
def handlisting(n):
    L = [str(i) for i in range (int("1"*n), int(12345679 * (10**(n-8))) + 1)]
reg = "1{1,4}(2{1,4}(3{1,4}(4{1,4}(5{1,4}(6{1,4}(7{1,4}(8{1,4}(9{1,4})?)?)?)?)?)?)?)?\Z"
return list(filter(re.compile(reg).match, L))

I think that I can do better because this one is pretty slow, and it doesn't delete those that are the same than other if read starting by the end (it will return "112234" and "123344", or "11112" and "12222")
EDIT : It goes a little faster with a condition like this :
L = [str(i) for i in range (int("1"*n), int(12345679 * (10**(n-8))) + 1) if \
    i%10 >= (i//10)%10 and i%100 >= (i//10)%100 and i%1000 >= (i//10)%1000 and i%10000 >= (i//10)%10000]


text:
Q: JGraph has unresolved AttributeMap on precompilation I am writing a first VERY simple class to see if my install can build something. So this is what I have
import org.jgrapht.ListenableGraph;
import org.jgrapht.ext.JGraphModelAdapter;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.ListenableDirectedGraph;

public class Some<JGraph> {

private Some() {
        ListenableGraph g = new ListenableDirectedGraph( DefaultEdge.class );

        JGraph graph = new JGraph(new JGraphModelAdapter( g ));
    }
}

I am working in Eclipse and I have jgrapgt-core, jgrapht-ext, jgraphx and jgraphx-3.2.2.0 setup as user libraries.
My problem is when I try to create the JGraphModelAdapter I get the error:
The type org.jgraph.graph.AttributeMap cannot be resolved. It is indirectly referenced from required .class files

Any help would be great.

A: JGraphT uses the old JGraph 5 library for visualization. org.jgraph is JGraph 5, com.jgraph is JGraphX.
Replace the jgraphx libraries with those from JGraph 5. JGraph 5 is on Github here.


text:
Q: StoryBoard image from referenced folder I have been trying to get images in my referenced folder(blue folder) in Storyboard. But I haven't had any luck. I tried putting something like this in the image field "images/image.png" but apparently it doesn't work.
Anybody ever encountered the same problem?


text:
Q: PySNMP can not recognize response i am using the following simple script:
from pysnmp.entity.rfc3413.oneliner import cmdgen

errorIndication, errorStatus, errorIndex, \
varBindTable = cmdgen.CommandGenerator().bulkCmd(
            cmdgen.CommunityData('test-agent', 'public'),
            cmdgen.UdpTransportTarget(('IP.IP.IP.IP', 161)),
            0,
            1,
            (1,3,6,1,2,1,4,24,4,1,2,169,254)
        )

if errorIndication:
   print errorIndication
else:
    if errorStatus:
        print '%s at %s\n' % (
            errorStatus.prettyPrint(),
            errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
            )
    else:
        for varBindTableRow in varBindTable:
            for name, val in varBindTableRow:
                print '%s = %s' % (name.prettyPrint(), val.prettyPrint())

Using snmpwalk from command line to this device returns expected result. But
script returns No SNMP response received before timeout. If i omit this OID then everything works fine.
So the problem is in this OID
Here tcpdump stats:
/usr/sbin/tcpdump -nn -vv -s0 -A host HOST and udp

tcpdump: listening on eth0, link-type EN10MB (Ethernet), capture size 65535 bytes

12:15:31.494920 IP (tos 0x0, ttl  64, id 0, offset 0, flags [DF], proto: UDP (17), length: 77) IP.IP.IP.IP.47911 > IP.IP.IP.IP.161: [bad udp cksum 4b7d!]  { SNMPv2c { GetBulk(34) R=8993731  N=0 M=1 .1.3.6.1.2.1.4.24.4.1.2.169.254 } }
E..M..@.@.I..]<..]</.'...9.S0/.....public."....;.......0.0...+..........).~..

12:15:31.495666 IP (tos 0x0, ttl  64, id 0, offset 0, flags [DF], proto: UDP (17), length: 98) IP.IP.IP.IP.161 > IP.IP.IP.IP.47911: [udp sum ok]  { SNMPv2c { GetResponse(55) R=8993731  .1.3.6.1.2.1.4.24.4.1.2.169.254.0.0.0.0.255.255.0.0.0.0.0=[inetaddr len!=4]0.0.255.255.0.0.0.0 } }
E..b..@.@.I..]</.]<....'.N.\0D.....public.7....;.......0)0'..+..........).~.............@.........

12:15:32.500226 IP (tos 0x0, ttl  64, id 0, offset 0, flags [DF], proto: UDP (17), length: 77) IP.IP.IP.IP.47911 > IP.IP.IP.IP.161: [bad udp cksum 4b7d!]  { SNMPv2c { GetBulk(34) R=8993731  N=0 M=1 .1.3.6.1.2.1.4.24.4.1.2.169.254 } }
E..M..@.@.I..]<..]</.'...9.S0/.....public."....;.......0.0...+..........).~..

12:15:32.500624 IP (tos 0x0, ttl  64, id 0, offset 0, flags [DF], proto: UDP (17), length: 98) IP.IP.IP.IP.161 > IP.IP.IP.IP.47911: [udp sum ok]  { SNMPv2c { GetResponse(55) R=8993731  .1.3.6.1.2.1.4.24.4.1.2.169.254.0.0.0.0.255.255.0.0.0.0.0=[inetaddr len!=4]0.0.255.255.0.0.0.0 } }
E..b..@.@.I..]</.]<....'.N.\0D.....public.7....;.......0)0'..+..........).~.............@.........

As we can see, device returns response .1.3.6.1.2.1.4.24.4.1.2.169.254.0.0.0.0.255.255.0.0.0.0.0=[inetaddr len!=4]0.0.255.255.0.0.0.0, but nothing happens and pysnmp just continue to try the value of this OID again and again.. snmpwalk recognizes this response as IP ADDRESS 0.0.255.255
Can you guys help me? Thanks in advance and sorry my english.

A: Your SNMP Agent seems to produce broken SNMP messages. While IPv4 address is four-octets long, your Agent reports eight-octets value.
As per SNMP RFCs, pysnmp drops malformed SNMP messages and retries original request a few times in hope to get correct response.
To make pysnmp working with specifically malformed IP address values you could patch its IpAddress class at runtime to make it taking just the four leading octets from a possibly longer initializer:
>>> def ipAddressPrettyIn(self, value):
...   return origIpAddressPrettyIn(self, value[:4])
...
>>> origIpAddressPrettyIn = v2c.IpAddress.prettyIn
>>> v2c.IpAddress.prettyIn = ipAddressPrettyIn
>>>
>>> msg, rest = decoder.decode(wholeMsg, asn1Spec=v2c.Message())
>>> print msg.prettyPrint()
Message:
version='version-2'
 community=public
 data=PDUs:
 response=ResponsePDU:
  request-id=6564368
  error-status='noError'
  error-index=0
  variable-bindings=VarBindList:
   VarBind:
    name=1.3.6.1.2.1.4.24.4.1.2.169.254.0.0.0.0.255.255.0.0.0.0.0
    =_BindValue:
     value=ObjectSyntax:
       application-wide=ApplicationSyntax:
       ipAddress-value=0.0.255.255


text:
Q: How to save and load history in powershell PSReadLine module? I'm using great PSReadLine module for Powershell and I really like that is persist my history of commands. But I need to reinstall my system. What is the easiest way to save this history (probably to file) an load it after fresh install of PSReadLine?

A: PSReadline module save command history in file. All you need is to backup that file and restore it after reinstalling your system. You can get file name of history file by following command:
(Get-PSReadlineOption).HistorySavePath