text:
Q: How to replace a value in a file with other value in Python I am writing a program in Python to search for value1 in column1 from a table which is in a file and if it exists, replace value2 in the same row of the table. The table has values in rows and columns separated by space. The first three lines of file contain text so in my code I have skipped first three lines and searched from the first element of first column. I have written the code in python( beginner in python). I am using replace function to replace value2 with new value. There is no error but the replace method is not working. The value is not modified in the file. I searched for similar questions in stackoverflow and implemented it but couldn't land at the correct output. It would be of great help if you could help me with this. Thanks in advance.
Skip first three header lines...
0  2.00000E-01  2.00000E+00  1.00000E-01  1.00000E-01  0.00000E+00  1.00000E-01    5315.58609617651
5  8.61341E-02  9.32377E-01  1.03878E-01  9.66092E-02  0.00000E+00  1.31608E-01    4874.21137697405
10  9.01592E-02  1.01589E+00  1.02249E-01  1.16872E-01  0.00000E+00  1.37603E-01    4868.99427672864
14  9.16065E-02  1.02727E+00  1.02914E-01  1.15918E-01  0.00000E+00  1.34975E-01    4868.85701581641
-1000000000  9.16065E-02  1.02727E+00  1.02914E-01  1.15918E-01  0.00000E+00  1.34975E-01    4868.85701581641
-1000000001  4.76910E-03  5.52689E-02  9.21654E-03  2.79153E-02  1.00000E+10  2.92135E-02   0.000000000000000E+000
-1000000004  0.00000E+00  0.00000E+00  3.20802E-01  3.40467E-01  0.00000E+00  3.67390E-01   0.000000000000000E+000
-1000000005  0.00000E+00  0.00000E+00  1.43648E-02  4.09956E-02  1.00000E+10  3.97582E-02   0.000000000000000E+000

My code:
    #python
    import sys
    # To open a file foce.ext and read the contents
iteration=[]
obj_value=[]
with open('ex_foce.ext','r+') as file:
#to skip first three lines and store the elements in 1st and 8th column in two arrays
    line1=file.readlines()[2:]

    for line in line1:
        if line:
            information=line.split()
            iteration.append(information[0])
            obj_value.append(information[7])
    print(line1)

    print(iteration)

    print(obj_value)
    pos=iteration.index('-1000000000')
    print(pos)
    #replacing value2 by 1.0
    obj_value[pos]=1.0
    print(obj_value[pos])
    old_value=obj_value[pos]
    line_number=pos
    x=line1[line_number]
    file.write(x.replace( str(old_value), "1.0" ))

file.close()

A: When you do line1=file.readlines()[2:], the "cursor" moves to the end of the file. Then you ask to write the line with the replaced value, so isn't it copied at the end of the file instead of being just modified in place? Maybe you miss a file.seek(...) call before writing.

A: If my understanding of the question is correct, you want the following:
Edit1, after clarification via comment
Edit2, to preserve preliminary information
# ... define value1, value3 ...
with open('ex_foce.ext') as f:
    lines = f.readlines()
    prelims = '\n'.join(lines[ : 2])
    lines = lines[2: ]
toWrite = ''
for line in lines:
    if line.startswith(value1):
        toWrite += ' '.join(line.split()[ : -1]) + value3 + '\n'
    else:
        toWrite += line + '\n'
with open('ex_foce.ext', 'w') as f:
    f.write(prelims + '\n' + toWrite);

Replace value1 and value3 as required.
Hope this helps.

A: A clean way to do it is;

*

*Open the file for reading

*Read all the lines from the file.

*Close the file

*Manipulate the lines how you want

*Open the file for writing (this will truncate the file)

*Write the changed files back to the file

*Close the file

You could open the file for reading and writing, and then use seek to go back to the beginning. But that would leave garbage at the end of the file if the new contents are smaller than the old one.

A: with open('ex_foce.ext','r+') as f:
    lines = f.readlines() # don't slice, we need to use all lines later
    for ind, line in enumerate(lines[3:]): # keep track of the index of each line using enumerate from line 4 to the end
        spl = line.split()
        if (spl[0]) == '-1000000000': # if we find value
            lines[ind] = line.replace(spl[7],"1.0") # replace line in lines at ind/index with updated value
    f.seek(0) # go back to start of file
    for line in lines: # write updated lines
        f.write(line)

A: I think the problem lies in the fact that you want to use the r+ opening mode for reading and writing. Even to change just one character in your file, here is the best way to proceed (I have written thousands of these):
f = open("ex_foce.ext","r")        # original file for reading
g = open("ex_foce_mod.ext","w")    # "output", modified file
for _ in range(3):
    g.write(f.readline())          # copy header lines
for line in f:
    L = line.strip().split()
    if L[0]=='-1000000000': L[7] = '1.0'
    g.write(' '.join(L)+'\n')
f.close()
g.close()

This will

*

*avoid losing data from the original file if the program fails;

*always produce the result you want without any problem;

*never load the entire file in memory (as readlines() does);

*not bother about the line index where you found the result (although you can get it using enumerate on f instead).

When finished sucessfully, you can remove the original manually (or with os.remove/shutil.rmtree). Forget about in-file editing, although it seems more intuitive at first. If you are afraid of leaving a lot of temporary files in the process, use appropriate tools such as tempfile.


text:
Q: Probability: What is the mathematical meaning of "or" in this sentence? I'm having trouble understanding the description of the event in italics (with P = 0.8) in the question below.
"The probability that an American industry will locate in Shanghai is P(S) = 0.7.
The probability that it will locate in Beijing is P(B) = 0.4.
And the probability that it will locate in either Shanghai or Beijing or both is 0.8.
What is the probability that the industry will locate: (a) in both cities? (b) in neither city?"
Doubt: Why the answer to (a) isn't P = 0.8?
The question itself says that "the probability that it will locate in either Shanghai or Beijing or both is 0.8".
Isn't it saying P(A∪B) = P(A∩B) = 0.8?
I've found many solutions available and the answers are  (a) 0.3 and (b) 0.2 but I still cannot understand why it is not 0.8.
Thanks.

A: It's actually saying $P(A \cup B) = .8$; from here, the probability that it will locate in both is $P(A \cap B)$ since it is asking that both event $A$ and event $B$ hold.  To get $P(A \cap B)$, utilize the formula:
$$P(A \cup B) = P(A) + P(B) - P(A \cap B).$$

A: Recall that the union of sets $A$ and $B$ consists of things that belong to either $A$ or $B$ or both. This is exactly the wording in your problem. By contrast, "$A$ or $B$, but not both" is an exclusive "or," so you have to remove everything that's in both $A$ and $B$, i.e., it corresponds to $(A\cup B)\setminus(A\cap B)$.
This is also why you have the inclusion/exclusion formula $\Pr(A\cup B) = \Pr(A)+\Pr(B)-\Pr(A\cap B)$. If you simply add the probabilities of $A$ and $B$ together, you double-count all of the elements they have in common: they've already been accounted for in $\Pr(A)$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Two continuous functions such that $f(z)^2=g(z)^2=1-z^2$ I need to find a domain $D$ and two continuous functions $f$ and $g$ such that $$f(z)^2=g(z)^2=1-z^2$$ for all $z\in D$.
This is what I tried.  Consider $$h(z)=e^{{1/2}L(z)}$$ where $L$ is a branch of logarithm such that $$L(z)=\log|z|+iArg(z)$$. And $D$=$\mathbb{C}$\ {$z|1-z^2 \in(-\infty,0]$}. This is all I could think of. Am I on the right track? Thanks

A: If you just need to find some domain $D$ in which $f$ and $g$ are to live, the unit disk will do nicely. When $|z|<1$, the real part of $1-z^2$ is positive. In the right half plane  the principal branch of square root is holomorphic (it is defined there as $re^{i\theta}\mapsto \sqrt{r}e^{i\theta/2}$ for $-\pi/2<\theta<\pi/2$), allowing for a direct definition of $f(z)=\sqrt{1-z^2}$ and $g(z)=-\sqrt{1-z^2}$.  (I assume that taking $f\equiv g$ would be somehow cheating.)
There are some larger domains too. Any simply connected domain not containing $\pm 1$ would do, but perhaps with a less direct argument.


text:
Q: Room doesn't detect @Typeconverters This is my only Entity:
    @Entity(tableName = "sticker_packs")
    class StickerPack(
        @PrimaryKey(autoGenerate = true)
        val identifier: Int = 0,
        var name: String,
        var publisher: String,
        @TypeConverters(StickerConverter::class)
        private var stickers: List<Sticker> = emptyList())

This is my custom Sticker class:
    data class Sticker(
    val emojis: List<String>,
    var imageDir: String,
    var size: Long = 0L)

This is my Database class:
@Database(entities = [StickerPack::class], version = 1)
//I get this same error with or without my Typeconverters here
@TypeConverters(StickerConverter::class)
abstract class StickerPacksDatabase: RoomDatabase() {

    abstract val stickerPacksDao: StickerPacksDao

    companion object{
        @Volatile
        private var INSTANCE: StickerPacksDatabase? = null

        fun getInstance(context: Context): StickerPacksDatabase{
            synchronized(this){
                var instance = INSTANCE
                if(instance == null){
                    instance =
                        Room.databaseBuilder(context.applicationContext, StickerPacksDatabase::class.java, "sticker_packs_database")
                            .build()
                    INSTANCE = instance
                }
                return instance
            }
        }
    }
}

And this is my typeconverter
    class StickerConverter {
    @TypeConverter
    fun stickersToJson(stickers: List<Sticker>): String = Gson().toJson(stickers)
    @TypeConverter
    fun jsonToStickers(json: String): List<Sticker> = Gson().fromJson(json)

    private inline fun <reified T> Gson.fromJson(json: String): T = fromJson(json, object: TypeToken<T>() {}.type)}

I'm not trying to do anything fancy just converting a list into a string with Gson, yet when trying to build the project I get the following error:

Cannot figure out how to save this field into database. You can consider adding a type converter for it.

But that's exaclty what I'm trying to do. I may have made a mistake somewhere but I can't seem to find it. I tried moving the @TypeConverters notation everywhere posible and the problem persists

A: You need to add the @TypeConverters annotation to the AppDatabase class so that Room can use the converter that you've defined for each entity and DAO in that AppDatabase:
Database(entities = arrayOf(Sticker::class), version = 1)
@TypeConverters(StickerConverter::class)
abstract class AppDatabase : RoomDatabase{
}


text:
Q: Rails, leaving comments in application.html.erb I dont know why i cant leave comments , they show up on my website, p.s,  I dont really know anything about code, just following a template for fun
I currently dont have a website or email to link to, so i tried to leave a comment to block examples so they dont show up on my page, but they do

Social

      #
WebsiteName

      #
MyEmail

A: If it is plain html, the way to comment a line is:

See The Importance of Correct HTML Commenting for more details.
If it is ruby code in the view, the way to comment a line is:
<%# This is a great comment! %>

See https://stackoverflow.com/a/2774858/429758 for details.

A: Comment block like this:


text:
Q: how to retrieve data from database and compare it if there is a match using IF ELSE. VFP 9 how to compare if the data is already exists in database in foxpro 9.
IF(if found)
 employee already exist.
ELSE
 insert employee into database.

A: Your question is too vague on "already exists".  What if you are looking for an employee "John Smith" and coincidentally you are a large organization where there are SEVERAL "John Smith" names employed... Do you have other criteria?  Such as a social security number, date of birth info, etc?  If so, you could run a query something like.
lookForSSN = "123-45-6789"
use in select( "C_IsOnFile" )
select SomeIDColumn ;
   from YourEmployeeTable ;
   where SocSecNum = lookForSSN;
   into cursor C_IsOnFile

if reccount( "C_IsOnFile" ) = 1
   */ Already on file, you can update it
   update YourEmployeeTable;
      set FirstName = FirstNameVar,;
          LastName = LastNameVar,;
          DoB = DoBVar,;
          etc = etcVar;
      where ;
         SSN = lookForSSN
else
   */ Not on file, add it
   insert into YourEmployeeTable ;
      ( FirstName, LastName, DoB, SSN, etc );
      values;
      ( FirstNameVar, LastNameVar, DoBVar, lookForSSN, etcVar )

endif
*/ close temp cursor when finished
use in select( "C_IsOnFile" )


text:
Q: Errors when using MomentJS in Angular Typescript library I'm building an Angular (2+) component library using jvandemo/generator-angular2-library as a starter, which uses Rollup as a module builder. The component I am creating in the library uses MomentJS.
I've had various build issues with the inclusion of MomentJS.
I first used import moment from 'moment'; to import moment into the component, but that produces the following error at build;
[17:26:28] Starting 'ngc'...
Error at /Users/chris/angular-library/.tmp/components/my-library/my-component.component.ts:6:8: Module '"/Users/chris/my-library/node_modules/moment/moment"' has no default export.

I found this SO question that said to use import * as moment from 'moment'; however with that I get;
'moment' is imported by build/components/my-component.component.js, but could not be resolved – treating it as an external dependency

events.js:182
      throw er; // Unhandled 'error' event
      ^
Error: Cannot call a namespace ('moment')
    at error (/Users/chris/angular-library/node_modules/rollup/dist/rollup.js:185:14)

As far as I can tell these are the only two options and I can't get either to work, what am I missing?
Edit
I've added this issue to the library's Github repo that contains minimalistic replication steps

A: To whoever finds this in 2018+, with Angular6 and current @angular/cli:
Today I ran into this and found solution here.
import * as moment_ from 'moment';
const moment = moment_;

Now the library compiles OK for me.

A: The error is very clear and specific

Error: Cannot call a namespace ('moment')
      at error (/Users/chris/angular-library/node_modules/rollup/dist/rollup.js:185:14)

This is per the ES Module Specification.
That means the following is an invalid way to import moment, or anything you intend to call, because a module namespace object, such as that created by * as ns may not be called.
import * as moment from 'moment';

The correct form is the form that ngc is raising an error on
import moment from 'moment';

Firstly to make this work, you need to specify the --allowSyntheticDefaultImports flag.
tsconfig.json
{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true
  }
}

Assuming that ngc will recognize the option, you still have an additional problem to work out.
The flag above is for users of tools such as SystemJS or Webpack which perform the synthesis, allowing such code to typecheck.
As of TypeScript 2.7, you can now specify the --esModuleInterop flag to have the language provide the synthesis as part of the transpilation process.
{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true
  }
}

Note that if you are using a version of TypeScript prior to 2.7 and if you are compiling to CommonJS, AMD, or UMD modules (e.g. with --module commonjs) the correct import syntax is rather
import moment = require('moment');

The import = require syntax is a TypeScript specific construct, now largely unnecessary. It exists to acquire both the type and the value of the module exports of an AMD, CommonJS, or UMD module. The "and" is important because a const, var, or let = require invocation only creates a name in the value space not in the type space.

A: In the sample directive I had no problem compiling when I used the following:
import { Directive, ElementRef } from '@angular/core';
import * as moment from '../node_modules/moment/moment';
@Directive({
  selector: '[sampleDirective]'
})
export class SampleDirective {

  constructor(private el: ElementRef) {
    moment.isDate('test');
  }

}

The files are compiled from a build directory that is a sub-dir off the root.
You do get a further warn about "this", mentioned here:
https://github.com/rollup/rollup/issues/794
I need to say in the gulfile that the library is external:
  external: [
    '@angular/core',
    '@angular/common',
    'moment'
  ],

And from the github link, you should add a onwarn block to both rollup sections:
That is section 'rollup:umd' and 'rollup:fesm'
onwarn: function(warning) {
    // Skip certain warnings

    // should intercept ... but doesn't in some rollup versions
    if ( warning.code === 'THIS_IS_UNDEFINED' ) { return; }

    // console.warn everything else
    console.warn( warning.message );
},

Does that get you any further?


text:
Q: Excel VBA - Use Application.Caller to get cell coords for an image I am trying to create a script that has a "delete tool" button. A tool will take up 5 rows. So, my code will delete the 5 rows when the X button is hit, and also will delete the X button because it is no longer necessary.
The only issue I am having is how do I find the cell address of the picture that was clicked? Below is the code I have begun to use.
Sub DeleteRow()

    Dim Check As Integer
    Dim r As Range
    Dim m As Picture
    Dim strCallerTyp As String

    strCallerTyp = TypeName(Application.Caller)

    Select Case strCallerTyp
        Case "String"
            Check = MsgBox("Are you sure you want to remove this tool?", vbYesNoCancel, "Delete Tool")
            If (Check = 6) Then
                MsgBox Sheets("sheet1").Shapes(Application.Caller).TopLeftCell '*THIS LINE*'
            End If
        Case "Error"
            MsgBox "Error"
    End Select
End Sub

Why is this line (marked in code):
MsgBox Sheets("sheet1").Shapes(Application.Caller).TopLeftCell
opening a message box that says "Excel" instead of a coordinate?
TIA!

A: add .Address to the end of the line
MsgBox Sheets("sheet1").Shapes(Application.Caller).TopLeftCell.Address
Hth,
Ojf


text:
Q: Why Pipeline Failed when there's test case failed i'm running robotframework in Gitlab-CI.
the problem i'm facing is, if there's any test case failed on the run, it will failed the pipeline too. so how to prevent the pipeline to failed? because the test failed, not the entire build process.
for now, this is how i run the robotframework on gitlab-ci.yml
- robot --exitonfailure -i "android-test" --outputdir ./output Android/Androidtest.robot

for example, i have 3 test cases on Androidtest.robot Test Suite:
1. register
2. fillin_profile
3. checkout_order
if register case and fillin_profile passed, but checkout order failed, the Ci pipeline will failed. i don't want that to be failed, because on the next job is to send the robotframework test report to gdrive, and it will never sent if the pipeline failed.
is that because i add --exitonfailure parameter btw? how to solve this?

A: Replace  --exitonfailure with --nostatusrc.
If there are test failures, robot will exit with exitcode other than 0. Gitlab and for that matter every ci ever, looks if any command it executes with exitcode other than 0 and thinks that there was a failure.  With --nostatusrc robot will always exit with 0 and thus your ci doesnt think there where failures.
Do consider that if you go with suppressing exit codes, you either loose the ability to mark the job within CI as failed if there was test failures unless you provide some other mechanism to do that if you happen to need such feature.

A: The whole point of CI is to fail when tests fail.
Uploading your test results or reports shouldn't be an extra job in the pipeline. I don't know about robotframework but GitLab supports publishing of artifacts after failed tests.
https://docs.gitlab.com/ee/ci/junit_test_reports.html


text:
Q: how to this database schema? design  the Database  schema  for  shipment company based on the following requirement with its constraints that maintains the data integrity , and write the SQL command for that .
•   The shipment system  contain information about the suppliers, items, shipments  as follows :
Supplier name with maximum 100 character , not allowed to have more than supplier, supplier name should not be  left empty and the name must not be repeated.
Supplier number   must not repeated for each supplier ,The nationality of the supplier almost is Jordanian and the Jewish nationality not allowed to deal with.
The shipment system contain information about the items as follow:
Item number which will not exceed the 99  items and this item number will not repeated for each item ,item name should  not  be repeated and  should not be empty, the total available quantity of this item in the store which must be 0 if the  user does not enter the initial quantity.
Each supplier could supply us with one item or more, which  is necessary to know the items for each supplier and the starting dealing date for supplying  the item. The item could be supplied  from more than one supplier .
The shipment system register the important  transaction information about the quantity of items that  supplied by the supplier with the shipment date  for each transaction .  each shipment transaction could have more than one item. ??

A: First pick out the nouns.
Shipment, Item, Supplier, Nationality

These are your entities, then find attributes of these entities e.g.
Item :: Number, Name, Supplier

Pay attention to the attribute domain, you will probably want to constrain to these.
Work out how these entities relate e.g.
Item (m:n) Supplier

For many to many relationships normalize with junction tables.
Go over an pick out business constraints e.g.
Jordanians and Jews cannot trade with each other

these may require triggers to implement.


text:
Q: code inside async function executes before the code that follows it I'm currently exploring the concept of async/await in javascript.I know that async function returns a promise which supposed to resolve in a future time and it doesn't block the natural execution of code.Here I have a code which i wrote to test the async execution of javascript.
console.log("1")
async function asyncFunc(){
  for(i=0;i<10000000;i++){
  }
  console.log("3")
}
asyncFunc().then(()=>{console.log('4')});
console.log("2");

I except the code will be executed in the following fashion:

first console.log() prints 1
secondly async function is called. As async code is non blocking,last console.log() will execute and thus prints 2 in the console.
After that console.log() inside async function will be executed and will print 3 in console.
lastly the promise will be resolved and console.log() inside then will be executed and prints 4.
so expected output : 1,2,3,4
but in reality I get output as 1,3,2,4.

why it behaves like this and not the way I expected

A: The function doesn't return a promise until it has finished running (unless you await another promise inside it).
The loop runs (blocking everything), then console.log("3") is evaluated, then it returns a promise.
The calling function continues to run (logging 2).
Finally, the event loop is freed up and the function passed to then is called.
Marking a function as async doesn't turn synchronous code inside it into asynchronous code.

A: Late answer here, and Quentin is exactly right, but it's helpful sometimes to diagram these things. Let's look at really simple async function:
async function foo() {
    console.log("a");
    await something();
    console.log("b");
    return 42;
}

That function has two parts:

*

*A synchronous part: Everything up to (but not including) the first await or return (or if it just ends). So in the above, that's the console.log("a"); and the call to something (but not the bit waiting for its result).

*An asynchronous part: Anything following that first await.

If we were to rewrite that function with explicit promises, it would look something like this (hand-waving away details):
function foo() {
    console.log("a");
    return something().then(() => {
        console.log("b");
        return 42;
    });
}

So looking at your function:
async function asyncFunc(){
  for(i=0;i<10000000;i++){
  }
  console.log("3")
}

...we can see that all of the code in the function is in its initial synchronous part, and the promise it returns will be resolved with undefined.
So why do async functions have a synchronous part? For the same reason the executor function you pass into new Promise runs synchronously: So it can start its work right away.
Suppose we wanted to do an async wrapper around fetch where we expect a JSON response:
async function fetchJSON(...args) {
    const response = fetch(...args);
    return response.json();
};

If that didn't have a synchronous part (the call to fetch(...args)), it would never do anything and its promise would never be settled.


text:
Q: Multiplication table using recursion without loops I've received an assignment to write a recursive function that receives two integersd from the user: x and y and  prints out the multiplication table up to the number x*y.
the prototyping of the function must be exactly like: void mult_table (int x, int base, int y)
(base gets 1 upon the first time that the function is called).
for example, if x=4 and y=5, the output will be:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20

note that no loop can be used inside the function, but additional recursive functions can be used if needed.
my problems are:
 1. how to iterate base correctly in lines 2 and greater, because in line 1 simple ++ works, but for the second line i already need
 2. that I can't think about a stopping case for the function, because each time that I'm about to print a new line the x and y values are changed.
I would be very grateful for any help, even suggestions of other ways to try and do it.
void mult_table (int x, int base, int y)
{
    int temp; //temp variable to hold x vlaue
    if (base <= y) //as long as base is less or equal to y, a number of line will be printed
    {
        printf(" %d", base); //using base with +1 incrementation
        mult_table(x, base+1, y);
    }
    else
    {
        printf("\n"); //start of a new line
        temp = x; //value of x is saved because it will be changed but it is still needed
        x= x+x*(1/(base-temp-1)); //new x value x+(x*1/original base of line) to reach the next x value
        y = y+y*(1/(base-temp-1)); //new y value y+(y*1/original base of line) to reach the next x value
        base = base - temp; //base is incrimented by 1 using this calcualtion
        mult_table(x, base, y); //recursdive call
    }
}

A: at each call increase base by one. Then you have to decompose base into f1 and f2 such that f1 * f2 is what you need to print at step base. I could give you the formula, but since this is an assignment I choose just to give you a hint: write in a table the values of base and the expected values of f1 and f2 and then you have to find 2 formulas to compute f1 and f2 based on base and y.
E.g. (for x=4 and y=5):
base  f1  f1
  1    1   1
  2    1   2
    ..
  4    1   5
  5    2   1
  6    2   2
    ..
and so on

Hints:

*

*notice that f2 kind of loops around a range. Think that the mathematical mod (% in c) does something like that.

*notice that f1 grows by one each k iterations. Think that / does something like that.

A: Write two recursive functions, one to recurse over the value of x and other to recurse over the values of y.
#include <stdio.h>

void mult_table_y(int x, int y)
{
   if ( y != 1 )
   {
      mult_table_y(x, y-1);
   }
   printf("%d ", x*y);
}

void mult_table(int x, int y)
{
   if ( x != 1 )
   {
      mult_table(x-1, y);
   }
   mult_table_y(x, y);
   printf("\n");
}

int main()
{
   mult_table(5, 5);
}


text:
Q: Как исправить ошибку: "warning C6385: Переполнение буфера при записи в ... "? // Массив должен выводится с доп. столбцом в начале  и после этого выдавать запрос на продолжение работы в программе или выход. Переполнение происходит после вывода массива с доп столбцом.
Main.cpp
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <conio.h>
#include "Functions.h"

int main(void)
{
    int n, m, i;
    int **a;
    char s = 'n';
    while (s != 'Y' && s != 'y')
    {
        printf("\n Enter the dimension of the matrix A[n][m]");
        printf("\n Number of columns N = ");
        scanf_s(" %d", &n);
        printf("\n Number of rows M = ");
        scanf_s(" %d", &m);
        if ((a = (int**)calloc(n, sizeof(int*))) == 0)
        {
            printf("\n Memory allocation failure Array **a \n");
            exit(1);
        }
        for (i = 0; i < n; i++)
            if ((a[i] = (int*)calloc(m, sizeof(int))) == 0)
            {
                printf("\n Memory allocation failure Array *a \n");
                exit(1);
            }
        ReadMatr(a, n, m);
        PrintMatr(a, n, m);
        AddColumn(a, n, m);
        freeArray(a, n);

    printf("Close program \n Y - Yes N - No \n");
    s = _getch();
    }
    return 0;
}

Functions.cpp
#include <stdio.h>
#include <stdlib.h>
#include "functions.h"

void ReadMatr(int **M, int n, int m)
{
    int i, j;
    for (i = 0; i<n; i++)
        for (j = 0; j<m; j++)
            M[i][j] = rand() % (n*m);
    return;
}

void PrintMatr(int **M, int n, int m)
{
    int i, j;
    printf("\n Output matrix A[%d][%d]:\n", n, m);
    for (i = 0; i<n; i++)
    {
        for (j = 0; j<m; j++)
            printf(" %4d ", M[i][j]);
        printf("\n");
    }
    return;
}

void AddColumn(int **M, int n, int m)
{
    int i, j, *Temp;
    int C1 = m + 1;
    for (i = 0; i < n; i++)
    {
        if ((Temp = (int*)realloc(M[i], C1 * sizeof(int))) == 0)
        {
            printf("Memory allocation failure after expanding for *a");
            exit(1);
        }
    }

    for (int i = m; i < C1; i++) {
        if ((M[i] = (int *)calloc(n, sizeof(int))) == 0) {
            printf("\nMemory allocation failure *a");
            exit(1);
        }

            for (j = m; j < C1; j++)
                M[i][j] = rand() % (n*m);
        printf("\n Output matrix with an additional column A[%d][%d]:\n", n, m);

        for (i = 0; i < n; i++)
        {
            for (j = C1; j > 0; j--)
            {
                 int Temp = M[i][j - 1];
                M[i][j] = M[i][j - 1];
                M[i][j] = Temp;

            }
        }

        for (i = 0; i < n; i++)
        {
            for (j = 0; j < C1; j++)
                printf(" %4d ", M[i][j]);
            printf("\n");
        }
    }
    return;
}

void freeArray(int **M, int n)
    {
    int i;
    for (i = 0; i < n; i++)
        {
            free(M[i]);
        }
    free(M);
    }

Functions.h
void ReadMatr(int **, int, int);
void PrintMatr(int **, int, int);
void AddColumn(int **, int, int);
void freeArray(int **, int);

Не могу понять как исправить эти ошибки

A: Корректная функция AddColumn:
void AddColumn(int **M, int n, int m)
{
    int i, j;
    int C1 = m + 1;
    //выделяем память под ещё один столбец
    for (i = 0; i < n; i++)
    {
        if ((M[i] = (int*)realloc(M[i], C1 * sizeof(int))) == 0)
        {
            printf("Memory allocation failure after expanding for *a");
            exit(1);
        }
    }
    //двигаем все столбцы на один вправо
    for (int j = C1-1; j > 0; j--){
        for (int i = 0; i < n; i++){
            int tmp = M[i][j];
            M[i][j] = M[i][j-1];
            M[i][j-1] = tmp;
        }
    }
    //заполняем крайний слева столбец случайными числами
    for (int i = 0; i < n; i++){
        M[i][0] = rand() % (n*m);
    }
    printf("\n Output matrix with an additional column A[%d][%d]:\n", n, m);
    for (i = 0; i < n; i++)
    {
        for (j = 0; j < C1; j++)
            printf(" %4d ", M[i][j]);
        printf("\n");
    }
    return;
}


text:
Q: PostMessage results in "...a call to pinvoke function has unbalanced the stack c#..." In a 32bit managed app I use Proecess.Start to load a 64bit .Net app.
Following that I PostMessage() from the 32bit app to the 64bit app using the MainWindowHandle.
The problem is that when the PostMessage() is called I get the error "A call to PInvoke function 'xxxx::PostMessage' has unbalanced the stack..."
After pressing continue everything works fine.
I am using VS 2017.
If I convert the 32bit app to 64bit no problem.
Also I don't get the problem when run the 32bit app outside the VS.
Both apps are in C#.
Can I just uncheck the PInvokeStackImbalance in MDA or is it something that I should "worry" about?
Thank you
Following is the code in a form to start a client app, dock its main form and set the handle of the current form to the client app.
    private const int SEND_HANDLE = WM_USER + 101;
    [DllImport("user32.dll", EntryPoint = "PostMessageA", SetLastError = true)]
    private static extern bool PostMessage(IntPtr hwnd, uint Msg, long wParam, long lParam);
    private void DoDock()
    {
        ProcessStartInfo psi = new ProcessStartInfo("test.exe");
        psi.Arguments = "";
        psi.UseShellExecute = false;
        psi.RedirectStandardOutput = true;

        pDocked = Process.Start(psi);

        while (hWndDocked == IntPtr.Zero)
        {
            pDocked.WaitForInputIdle(1000);
            Thread.Sleep(100);
            pDocked.Refresh();
            if (pDocked.HasExited)
                return;
            hWndDocked = pDocked.MainWindowHandle;  //cache the window handle
        }

        PostMessage(hWndDocked, SEND_HANDLE, this.Handle.ToInt32(), 0);
    }

A: This normally means that your pinvoke declaration is wrong. This website lists the correct declaration as:
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern bool PostMessage(HandleRef hWnd, uint Msg, IntPtr wParam, IntPtr lParam);


text:
Q: How to join cells filtered out from a column by values from another column? There is a two-column table containing keys in the first column and respective values in the second column. There are repeating keys in the first column, and so the same key can have multiple values. I need values for each key joined into a single cell. So in the end to have a table with no repeating keys in the first column, and joined values for each key in the second column.
I found an easy solution using a filter then transpose then join. But this is a one-line solution (formula has to be copied for each row). Is there a way to achieve this using an array formula? And without using scripts?

A: try:
=ARRAYFORMULA({SORT(UNIQUE(FILTER(A:A, A:A<>""))),
 REGEXREPLACE(TRIM(TRANSPOSE(QUERY(TRANSPOSE(
 IF(QUERY(QUERY(A1:B,
 "select count(A) where A <>'' group by A pivot B"),
 "offset 1", 0)<>"", QUERY(QUERY(A1:B,
 "select count(A) where A <>'' group by A pivot B"),
 "limit 0", 1)&",", )),,999^99))), ",$", )})


text:
Q: Finding record by custom primaryKey My model is defined as follow:
App.User = DS.Model.extend({
  primaryKey: 'username',
  username: DS.attr('string'),
  name: DS.attr('string')
});

My custom Adapter map:
DS.SocketAdapter.map('App.User', {
  primaryKey: 'username',
  username: DS.attr('string'),
});

I am testing this model out by typing on console:
App.User.createRecord({username:"user_1"});
var r = App.User.find("user_1");
console.log( r.serialize() );

>> Object {username: null, name: null ..... all null}

But it retuns a "null" Object. Also tested:
App.User.find({username:"user_1"});

But this is doing a remote request. I read that Ember Data does allow you to find records via attributes other than the ID.
So what I am doing wrong in telling Ember data my custom primaryKey?

A: I think your problem lies in the fact that you are defining username twice. if you map username from your json to your model's primaryKey trough your Adapter, then you should avoid to do the same on the model I guess. There are different approaches where to define the mapping, but the Adapter is the most appropriate place In your case, see here for more details: https://github.com/emberjs/data/blob/master/BREAKING_CHANGES.md#mapping
change your code like so and it should work:
// Model
App.User = DS.Model.extend({
  name: DS.attr('string')
});

// Adapter
DS.SocketAdapter.map('App.User', {
  primaryKey: 'username'
});

now try to create a new record
App.User.createRecord({username:"user_1", name:"foo"});

and then find the record by it's id as you already did:
var r = App.User.find("user_1");

this
console.log( r.serialize() );

should then give you at least:
>> Object {name: "foo" ...}

hope it helps


text:
Q: How would i add the ability to upload a picture to be a posts background on the show page in rails? So in rails I have post CRUDability made so far, I have markdown on my posts.
When I create the posts I also want to have the ability to upload a picture which will be displayed as the background of the post on the show page when the user clicks this. I know the question is a bit broad and could possibly be refined but I wouldn't know how to word it.


text:
Q: Displaying Computer Name at Application Startup We would like to display the name of the computer being used on our application without having to click on a label or use of a messege box.
Private Sub Label2_Click(sender As Object, e As EventArgs) Handles Label2.Click
    Label2.Text = My.Computer.Name
End Sub

The code above works but only when you click on the label.
How do we get it to just display as plan text.

A:   Private Sub Form1_Activated(sender As Object, e As System.EventArgs) Handles Me.Activated
        Label1.Text = My.Computer.Name
    End Sub

A: Add a constructor to the window containing the label and assign the text in there.
Public Sub New()

    ' This call is required by the designer.
    InitializeComponent()

    Label1.Text = My.Computer.Name
End Sub


text:
Q: How to create a series of integers in a dataframe only when there are no NaNs, and integers increasing by 1 unit? I have a dataframe that look like this:
data = pd.DataFrame([NaN, NaN, NaN, 0.5, 1.2, 2.7, 3.8, NaN, NaN, 0.1, 0.7, 2.3, NaN, NaN, NaN, NaN, NaN, 0.01, 0.4, 1.5, 2.8, 4.5, 5.6, NaN, NaN, NaN, NaN, NaN, NaN])

The extra column I need to create should look like this:
data = pd.DataFrame([NaN, NaN, NaN, 1, 1, 1, 1, NaN, NaN, 2, 2, 2, NaN, NaN, NaN, NaN, NaN, 3, 3, 3, 3, 3, 3, NaN, NaN, NaN, NaN, NaN, NaN])

Basically, when there are NaNs, the integer remains the same, and when not a NaN is found it should increment by 1 unit and be constant until another NaN is found.
Is there an elegant way to do this without going through every row individually? My dataframe is very large.

A: Let's consider this input data
NaN = np.nan
data = pd.DataFrame(
    [NaN, NaN, NaN, 0.5, 1.2, 2.7, 3.8, NaN, NaN, 0.1, 0.7, 2.3, NaN, NaN,
     NaN, NaN, NaN, 0.01, 0.4, 1.5, 2.8, 4.5, 5.6, NaN, NaN, NaN, NaN, NaN, NaN])

So the idea is to first create a Boolean column where it is not nan with notna.
m = data[0].notna()

Now, you can get the diff on this Boolean column to get True when it change from True to False or vice-versa. Keep the True only when it changes when notna with &m. Use cumsum to get the incremental integer and then where with the Boolean mask m to replace by NaN where it was Nan originally. So in one liner:
data['res'] = (m.diff()&m).cumsum().where(m)
print(data)
       0  res
0    NaN  NaN
1    NaN  NaN
2    NaN  NaN
3   0.50  1.0
4   1.20  1.0
5   2.70  1.0
6   3.80  1.0
7    NaN  NaN
8    NaN  NaN
9   0.10  2.0
10  0.70  2.0
11  2.30  2.0
12   NaN  NaN
13   NaN  NaN
...


text:
Q: How to set Package Manager Console to appear automatically When I used to use vs2015, the package manager console would always appear at the bottom when opening a solution.
I'm currently on vs2017, and wheneever I open a solution I need to open the console manually.
How can I set this to appear by default when opening vs?

A:
How can I set this to appear by default when opening vs?

This is related to your Visual Studio settings. If you close the package manager console window before you close the Visual Studio, that window would not appear by default when you open the Visual Studio again.
This is by design. So if you want to set the package manager console to appear by default when opening vs, you should make sure not close this window the last time you close Visual Studio.
If above not help you, please try to reset the Visual Studio window layout, go to Tools > Import and Export Settings > Reset all settings
Be sure you back up your settings before you do this. Then open the Visual Studio and open the window package manager console:

Hope this helps.


text:
Q: Android draw9patch throws NoClassDefFoundError I upgraded to Android SDK Tools r8 today and I can't seem to run the draw9patch tool.  I'm getting the following error:
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/jdesktop/swingworker/SwingWorker
at com.android.draw9patch.Application$1.run(Application.java:48)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:633)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Caused by: java.lang.ClassNotFoundException: org.jdesktop.swingworker.SwingWorker
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at sun.misc.Launcher$ExtClassLoader.findClass(Launcher.java:229)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
... 9 more

I'm running snow leopard and have jre (or jdk?) 1.6.
Any ideas how to get this working?  Thanks!

A: I have found a solution(Ubuntu 10.10, java-6-sun). Copy swing-worker.jar into /path_to_android_sdk/tools/lib. You can find swing-worker-1.1.jar in the same directory in SDK r7 or download it from here.


text:
Q: Java - Add padding to large images I need to add specific padding around large images and the current method I am using, as seen in the snippet below, is eating up memory. Opening the PNG sucks up ~300mb of memory right off the bat and making a copy of that pushes me past 700mb so I am looking for a way to do this without sucking up all available memory. Any suggestions?
...
BufferedImage img = ImageIO.read(new File("OldWorld.png"));
BufferedImage img2 = new BufferedImage(img.getHeight()+padding,img.getWidth()+padding, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img2.createGraphics();
g2.setPaint(new Color(0,0,0,0);
g2.fillRect(0, 0, img.getHeight()+padding, img.getWidth()+padding);
g2.drawImage(img, img.getHeight(),img.getWidth(), null);
...

A: There is no direct way to solve this.
Working with large images in Java consumes a lot of memory.
Some alternatives are:

*

*Pre-process your images with the netpbm library
http://netpbm.sourceforge.net/.
To pad an image use a command like:
pngtopnm OldWorld.png | pnmpad -black 48 -left 48 -top 48 | pnmtopng > padded.png

*Reduce the number of colors in your image so that you can use image type
BufferedImage.TYPE_INDEXED with only one byte per pixel instead of four.

*Use a several tiles instead of a single large image and work
with one tile at a time.  Then you avoid having a lot of image
data in memory.


text:
Q: How to split backup file using `pg_dump.exe` in windows I have tried following command to split backup file but it is always showing error illegal option split:
pg_dump.exe" -h localhost -p 5432 -U
postgres --inserts | split -b 2m – backup.sql -f "D:\post\filename.sql"
db_name

A: you use pipe (|) and unix split command as argument to pg_dump.exe. It won't work. Consider trying 7zip volumes for that. Or any other command line splitter


text:
Q: Calculate absolute values for resistor bridge to use with op amp lm358 I'm trying to make a simple thermostat using a thermistor and an Op Amp. The relevant part of my circuit diagram is shown below.

simulate this circuit – Schematic created using CircuitLab
R4 is the thermister and R1 is a variable resistor. I'm able to calculate the relative values of the four resistors to each other, but I don't know how to choose the absolute values. How do I decide what power of ten in ohms I should be working in? Ie should the resistors be around 10Ω, 1kΩ, 100kΩ etc.
I assume this decision relates to my power supply and the choice of Op amp, but I've no idea how to make a sensible choice.
Thanks,

A: Providing your inputs don't go outside the common mode range of the op-amp you are left with two criteria that are important, noise and bias currents. Making the resistors high in value increases the effects of bias and offset current therefore creating an offset voltage error. Having high value resistors also increases thermal noise voltages - this may also be unacceptable.
On the other hand, having values that are too low will impact on current drawn from the power supply. Decide what is an acceptable current to be taken from the power rail, check to see that it does not induce too much self-heating in the thermistor then look at the data sheet for the LM358 and see what possible effects offset and bias currents have in producing error voltages.


text:
Q: Autoloading namespaces I am creating my own MVC framework for a simple website and I want to use namespaces but I don't know how to autoload them. Here is what I tried so far:
I have a init.php file that has autoloading function:
    spl_autoload_register(function($class){
    $file = __DIR__ . '/../' . str_replace('\\', '/', $class) .'.php';
    echo $file;
    if (file_exists($file)) {
        require_once $file;
        echo 'yes';
    }

    use App\Core\App as App;

    $app = new App;

This code returns "yes" so it locates the App file.. But it also returns a fatal error: D:\xampp\htdocs\MVC\App/../App/Core/App.phpyes
Fatal error: Class 'App\Core\App' not found in D:\xampp\htdocs\MVC\App\init.php on line 28
Line 28 is $app = new App;
Here is how I am namespacing my App file:
    <?php

    namespace App\Core\App;

    class App
    {
    .....

The file structure is the following:
| App
|--| Core
|--|--| App.php
...
| init.php

Any ideas why?

A: Instead of making your own autoloader, just use the one, that comes built-in with composer. You just add the following segment in the composer.json file and it's done:
"autoload": {
  "psr-4": {
    "": "dir_where_namespaces_start...usually_src"
  }
}

Also, you can't really make and "mvc framework", because MVC architecture is what the application code implements and no the framework.


text:
Q: SQL- What is the lead_id , account_id and the number of days between lead created_date and the account created_date For each lead associated with an account, what is the lead_id, account_id, and the number of days between the lead created_date and the account created_date?
lead_id    created_date     industry
INT DATE    VARCHAR (25)

e.g. 2345566    2019-01-25  sales
account_id    created_date  lead_id
INTEGER DATE (YYYY-MM-DD)   INTEGER

e.g 34345564 e.g. 2019-03-14    123152
I have tried this
Select
Distinct Lead_id,
Distinct Account_id
Datediff(days,l.created_date,a.created_date)
From
Lead l
Join
Account a
On a.lead_id= l.lead_id

A: You don't need distinct for this.  Assuming you are using SQL Server:
Select Lead_id, Account_id
       Datediff(days, l.created_date, a.created_date)
From Lead l Join
     Account a
     On a.lead_id = l.lead_id;


text:
Q: Making part of the page(audio streamer) not post-back Basically, I have a webpage that will have a streaming music player/radio.
Right now, whenever something is done that initiates a postback, the music is also cut.
I think that the old way of doing it was to create a simple pop-up window of the player and from there, the music would play as long as it is needed, but is there any better - modern - way of archieving what I am after?
The page is written in PHP and the music player will be most likely done with HTML5, althought it is open.

A: Well there is not so much you can do here.
There is like 3 or 4 options to go:
1) Old school popup's.
2) Iframe based player (usually at the top or bottom of page).
3) Convert website to use Ajax for all that is reloading page.
4) Use flash (definitely not an valid option, but it is an option).
Personally i would go with option 2 for faster implementation and option 3 for sake of modern days and user experience. But it all depends ofc on the website you are building.
Good luck.

A: Well, you could go fully-blown scripting with AJAX, and fallback (non-JavaScript) to targeting your form post to a hidden iframe element.

A: The best way I can think to do that is to handle your postbacks with AJAX. That way there's never a page refresh when posting data. You can handle the data send and response through javascript, leaving the page (and the player) intact.


text:
Q: How to propagate properties in parent POM to child POM post build Have many shared libraries (jar) that use a common parent POM.
Parent POM has property log4j.version defined as 2.17.1
Child projects A and B have log4j dependency defined with version ${log4j.version}
mvn clean install works fine. But when I look at the generated artifact for projects A or B, their POM still says log4j version in dependencies section as ${log4j.version}. That won't have the desired effect of going with version 2.17.1 if other projects start using library A or B. What is a way to keep the version definition in parent, yet have the child projects specify the version in the built artifact?
And I don't want to add log4j dependency in parent POM because I have few child projects that do not need/use log4j at all. Also, that doesn't solve the problem because even then the child projects after build will not call out the dependency to log4j at all? Probably worse than what I have now

A: This behavior is expected.
Sub-module's pom-files not built like resources files with the property values resolved. They always refer to the parent-pom.
If you add some module A which is a sub-module (contains <parent> definition) to the project dependency, it will download the parent-pom, like transitive dependency, and will take the property value from the parent pom.
Look at some released pom in maven central (FasterXML Jackson), e.g.
property javax.activation.version defined in parent pom
https://repo1.maven.org/maven2/com/fasterxml/jackson/jackson-bom/2.13.1/jackson-bom-2.13.1.pom
and referenced in child pom
https://repo1.maven.org/maven2/com/fasterxml/jackson/jackson-base/2.13.1/jackson-base-2.13.1.pom


text:
Q: Javascript modules multiple instance Actually im just studying JavaScript modules. They are pretty easy but i got stuck in when it comes to multiple instances of single module
here is my code
var Mod = (function() {
    var ops;
    ops = function () {
        var Num;
        this.set = function (e) {
            Num = e;
            return this;
        };
        this.get = function() {
            return Num;
        };
    };
    return new ops();
})();

but when i do
console.log(a = Mod.set(1));
console.log(b = Mod.set(2));
console.log(a.get());  // output 2 :'(
console.log(a == b);    // true :/

i cant understand why this is happening? may be because Mod anonymous function only call one time but now my question how Jquery $ works?
as
a = $("div")
b = $("span")
console.log(a == b) // false

and how can i achieve this behavior with my Mod should i go for another programming technique? but i dont want to use new keyword thanks in advance!
here is the fiddle

A:
why this is happening? may be because Mod anonymous function only call one time

Yes, you understand it right. You only have one instance, single object, so a is indeed just another name for b.

but now my question how Jquery $ works?

jQuery constructs new instances properly (see the source code), by the way with new keyword which you don't want to use for some reason.
UPD. Here is one approach for correct instantiation:
var Mod = (function() {

    function ops(value) {
        this.value = value;
    }

    ops.prototype.get = function() {
        return this.value;
    };

    return {
        set: function(value) {
            return new ops(value);
        }
    };
})();

console.log(a = Mod.set(1));
console.log(b = Mod.set(2));
console.log(a.get());
console.log(a === b);


text:
Q: Openshift Jenkins pipeline I am looking for explanation for functions used in below Jenkins pipeline on openshift.

*

*builds.untilEach(1)

*it.describe()

*echo "Inside loop: ${it}"

*return (it.object().status.phase == "Complete")

node {
    stage('build') {
        openshift.withCluster() {
            openshift.withProject() {
              echo "Using project: ${openshift.project()}"
              def builds = openshift.selector("bc", "front-end-build").related('builds')
              builds.describe()
              timeout(5) {
               1. builds.untilEach(1) {
                2.    it.describe()
                 3.   echo "Inside loop: ${it}"
                   4. return (it.object().status.phase == "Complete")
                }
              }
            }
        }
    }
}

A: I'll try to give an overview of what the lines you mentioned mean:

*

*timeout(5) This means that the steps described within this part (between {}) need to finish within 5 minutes or else they will be terminated. This step will fail if any of the below actions take more than 5 minutes.

*builds.untilEach(1) Loops over all Builds related to the selector openshift.selector("bc", "front-end-build") above. This loop expects at least one build to be returned. It loops over the Builds and waits until the closure body (between {}) returns "true".

*it.describe() Describes the Build object that is currently being looped over / waited on.

*echo "Inside loop: ${it}" Write the Build object to stdout.

*return (it.object().status.phase == "Complete") Check if the Build that we are looping over is complete and return.
So basically, this loop will wait for all Builds related to the BuildConfig front-end-build to complete.


text:
Q: Keeping Qt translations up to date I am working on a C++ application, that uses the Qt library for implementing the GUI (we use cmake files to generate projects for VS). Lately, we are dealing with the internationalization of the application by using built-in Qt's features (Qt Linguist). The translation process is simple and straightforward and works great. The Qt Linguist tool can be used by a professional translator to translate files, automatically generated by Qt's tools (lupdate, lrelease).
Because applications are typically never really finished (upgrades, fixes, ...), I am wondering what is the best practice to ensure that all the translation files are always up to date. Is it better to have a person assigned to it or somehow automate it via post-build / pre-commit scripts? Is there some tool that might be useful?

A: We used the QT translator in my previous job. the up-to-date check was poorly done at that time but few things I'm doing in my current job may help:

*

*If I remember well, the string you define in code will be the default value if not precised in translator, so maybe you should define a default format like "MISSING TRANSLATION - ". So it will be easily detected by QA

*If you have some UI automated testing, adding new tests should include testing the translated strings of the application. Then a failing testcase should help you detect those missing messages (It's what I do today, my language file is in XML and my automation tool automatically compare strings from xml to the message from UI in all supported languages)

*You may have a pre-check script in your versionning tool. For example if the modifications contain a SetToolTip call, you may guess that a modification in translator is also needed... (just an idea, it can becomes really annoying if having a clean translation is time consuming).


text:
Q: visual studio .net forms How do I find the form in the designer window given the panel name in the container list? visual studio pro  2015
.net framework 4.8
forms How do I find the form in the designer window given the panel name in the container list?


text:
Q: Expressing complex numbers from the exponential form to the form $a+bi$ I am given the following question:

Evaluate $(6e^{i\pi/4}) \times(6e^{i\pi/4})$ and express the resulting complex number in the form $a + bi$.

I'm thinking I should use $e^{iz}=\cos(z)+i\sin(z)$, but I'm not quite sure. I can perform the multiplication without errors, but the problem is getting the answer in the correct form.
I would love some help with this.

A: First multiply and simplify:
$$(6e^{\frac{i\pi}{4}}) \times (6e^{\frac{i\pi}{4}}) = 36e^{\frac{i\pi}{2}}$$
You are correct that you can use $e^{iz}=\cos(z)+i\sin(z)$ to get an answer in the form that you want:
$$36e^{\frac{i\pi}{2}} =36(\cos(\frac{\pi}{2})+i\sin(\frac{\pi}{2}))$$
$$ = 36(0+i)=36i$$
Therefore, the answer is $36i$ (which is in the form $a+bi$ with $a=0$ and $b=36$ - as required).

Note: this uses the fact that $\cos(\frac{\pi}{2})=0$ and $\sin(\frac{\pi}{2})=1$

A: You can multiply them:
$(6e^{\frac{i\pi}{4}}) \cdot (6e^{\frac{i\pi}{4}}) = 36i$ ; USE: $e^{\frac{i\pi}{2}} = i$
Then, you can use $a+bi$ on the $36i$ is $0+36i$
By using Euler's Formula (mentioned in your question) it will be
$6(\cos(\frac{\pi}{4}) + i\sin(\frac{\pi}{4})) \cdot 6(\cos(\frac{\pi}{4}) + i\sin(\frac{\pi}{4})) = 0+36i$


text:
Q: Is binary search for an ordered list O(logN) in Elixir? For an ordered list, the binary search time complexity is O(logN). However in Elixir, the list is linked list, so in order to get the middle element of the list, you have to iterate N/2 times, which make the overall search O(NLogN).
So my question is:

*

*Is above time complexity correct?

*If it's correct, the binary search wouldn't make sense in Elixir, right? You have to iterate the list to get what you want, so the best is O(N).

A: Yes, there is little reason to binary search over a linked list because of the reason you stated. You need a random access data structure (usually an array) for binary search to be useful.
An interesting corner case might arise where the comparison of the elements is very costly, because for example they are just handles to remotely stored items. In that case binary search through a linked list might still outperform linear search, because while requiring more operations (O(N * log(N))) it requires less comparisons (O(log(N))) while linear search requires O(N) comparisons.


text:
Q: Operating Systems - File system on SSD vs Rotational Solid State Drives (SSD) pose new challenges and opportunities for designers and implementers of file systems. On the one hand, an SSd has no rotational delay and no seek time because no rotational media is involved. On the other hand, space is costlier: SSDs are 10-20 times more expensive per byte.
Assume - transfer time is the same as a typical traditional rotating disk.

A) Describe a strategy for implementing a file system on a rotational device
B) How would that strategy change for an SSD? Be sure to discuss issues of latency and fragmentation in both, as well as main-memory demand.

A: A filesystem on rotational media is designed to minimize the amount of seeking that is needed to read the blocks that make up a file.  In the ideal case, the blocks of a file are contiguous on disk.  If a file is small enough, it will be placed in a single track.  If it won't fit in one track, the blocks will be placed in contiguous tracks.
The difficulty comes when files are deleted.  This creates non-contiguous free space on disk, otherwise known as fragmentation. Window's NTFS has a defragmentation utility to coalesce the free space and make it contiguous.  Linux filesystems like ext2 use other ways to avoid fragmentation.
SSDs don't have seek overhead, so fragmentation is not a performance issue.  A filesystem for SSDs would prioritize reducing writes to the device, since SSDs have a limit on how many times each block can be written.  SSDs controllers actually spread writes out over the entire device to spread out the wear due to writes.  Defragmenting an SSD is not needed and actually reduces the life of the device.
The part of the question about "main memory demand" does not make much sense.  I suppose rotational media would have more main memory demand because of the desire to schedule reads and writes to minimize seek latency.


text:
Q: what is the meaning of the error shown in DDMS regarding known host exception
Can you help me understand how I should debug this errors? What information would you get from this stack trace that might help you understand what is wrong with this code?
I assume andy_lockscreen is not my concern as it doesn't have anything to do with my app.
However what is the meaning of the errors with tag TiApplication and TiHttpClient?
How can I filter to see only errors and traces regarding my app?
I am developing android application using titanium
Thank you,
Ryan

A: UnkonwnHost means whatever is trying to connect to something online is unable to connect. Either the online content is down (unlikely given that it is google maps) or the device doesn't have a suffecient internet connection, or something else is blocking the connection (iptables perhaps, DroidWall will cause this type of error if you havn't white listed the application attempting to connect)
You can make a filter by clicking the Green "+" that is in the pane just off to the left of the screenshot you provided. Type in the Tag that you are using when you make Log statements within your app. That will narrow down the list to only Logs coming from your application.


text:
Q: How to Coerce multiple columns to factors at once for H2OFrame object? I am trying to follow the suggestion on question: "Coerce multiple columns to factors at once", but it does not work for an H2OFrame object, for example:
data <- data.frame(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10])))
data.hex <- as.h2o(data, destination_frame = "data.hex")
cols <- c("A", "C", "D", "H")
data.hex[cols] <- lapply(data.hex[cols], factor)

Produces the following error message:
Error in `[<-.H2OFrame`(`*tmp*`, cols, value = list(1L, 1L, 1L, 1L, 1L,  :
  `value` can only be an H2OFrame object or a numeric or character vector
In addition:
Warning message:
In if (is.na(value)) value <- NA_integer_ else if (!is.numeric(value) &&  :

the condition has length > 1 and only the first element will be used

If I try to coerce as factor one by one, it works. Another workaround is to coerce as factor first the data.frame, then convert it into H2OFrame object, for example:
data[cols] <- lapply(data[cols], factor)
data.hex <- as.h2o(data, destination_frame = "data.hex")

Any explanation why it happens or any better workaround?

A: The right way to do it is to use the H2OFrame apply() function, however, this produces the same error that @MKR mentioned.  I have created a JIRA ticket here.
In theory, this should work:
data.hex[,cols] <- apply(X = data.hex[,cols], MARGIN = 2, FUN = as.factor)

For now, the workaround is:
for (col in cols) {
  data.hex[col] <- as.factor(data.hex[col])
}


text:
Q: SlowCheetah not previewing transform on deployment profile I have a webjob that I am looking to transform the app.config on.  I have installed SlowCheetah and it works fine with a transform for release and debug versions.  However if I try to use it with the transformations for specific deployment profiles to azure, I get nothing on the preview transform.  The option is there, but nothing happens when I click it.  This also means that the standard app.config is applied on deployment.
Any help would be great,
Thanks

A: According to your description, I have installed the SlowCheetah and test it in my side, it works well.
So I suggest you could follow below steps to reinstall the SlowCheetah and try again.
1.Download it and install.
2.Add the app.config transform to your project, for example app.Debug.config and app.Release.config
3.Open your *.csproj file and you will find these lines (depending on the name and number of transformation you want :
<None Include="App.Release.config">
    <DependentUpon>App.config</DependentUpon>
    <TransformOnBuild>True</TransformOnBuild>
</None>
<None Include="App.Debug.config">
    <DependentUpon>App.config</DependentUpon>
    <TransformOnBuild>True</TransformOnBuild>
</None>

above these lines :
<None Include="App.config">
    <TransformOnBuild>true</TransformOnBuild>
    <SubType>Designer</SubType>
</None>

4. Reload your project and it should work.
The result is like this:

Update:
I guess you don't add the new build configuration to your web job application.
So you will find the preview is not work well.
I suggest you could follow below steps to add new build configuration.
1.Open configuration manager

2.Add new confiuration

3.Add transform

4.Preview


text:
Q: passing post data parameters in jax-rs and calling by ajax I've delved into StackOverflow for days and went through these links 1 and 2 and 3 but all to no avail.
I am a newbie in java web applications. I am using Tomcat 9.0.4 and Jersey 1.18 in my project. I want to pass 4 parameters as 4 points to a post web service written in JAX-RS and get back the area and perimeter in response. This is my server-side web service:
    @path("/geo")
    public class geonodes{
      static double area(double x1,double y1,double x2,double y2){
      //do area calculation
      }
      static double perimeter(double x1,double y1,double x2,double y2){
      //do perimeter calculation
      }
      @POST
      @Produces(MediaType.APPLICATION_JSON)
      public Response calculate(@QuerParam("x1") Double x1,@QuerParam("y1") Double y1,@QuerParam("x2") Double x2,@QuerParam("y2") Double y2){
        JSONObject obj = new JSONObject();
        obj.put("area",area(x1,y1,x2,y2));
        obj.put("perimeter",perimeter(x1,y1,x2,y2));
        result = JSONObject.toJSONString(obj);
        return Response.status(201).entity(result).build();
    }

and this is my ajax client-side call:
$.ajax({
    url:'http://localhost:8080/api/geo',
    type:'POST',
    dataType:'json',
    contentType:'application/json',
    data:JSON.stringify({x1:22.1,y1:44.19,x2:55.33,y2:49.72}),
    success:function(data){console.log(data);},
    error:function(errMsg){console.log(errMsg);},
});

I use a non-maven project including these jar files:

And this is my web.xml
    <servlet>
        <servlet-name>Geo Nodes API</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>

        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>example,com.fasterxml.jackson.jaxrs.json</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>

    </servlet>

    <servlet-mapping>
        <servlet-name>Geo Nodes API</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>CorsFilter</filter-name>
        <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CorsFilter</filter-name>
        <url-pattern>/api/*</url-pattern>
    </filter-mapping>

The response was always null and after a long search and google, I found the problem in parameters so in response I returned them. when I call the address by the postman the result returns correctly as below:

But invoking by ajax or another system, the parameters are always null.

Whenever I use something except @QueryParam i.e the class with getter and setter like below code the postman gets the 415 error either.
The Coordinats.java class:
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Coordinates {
    private Double x1;
    private Double y1;
    private Double x2;
    private Double y2;

    public Double getX1() {
        return x1;
    }
    public void setX1(Double x1) {
        this.x1 = x1;
    }
    public Double getY1() {
        return y1;
    }
    public void setY1(Double y1) {
        this.y1 = y1;
    }
    public Double getX2() {
        return x2;
    }
    public void setX2(Double x2) {
        this.x2 = x2;
    }
    public Double getY2() {
        return y2;
    }
    public void setY2(Double y2) {
        this.y2 = y2;
    }

}

The server-side code snippet:
import model.Coordinates;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

@Path("geo")
public class Geo {

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Coordinates request(Coordinates coordinates){
        Double x1 = coordinates.getX1();
        Double y1 = coordinates.getY1();
        Double x2 = coordinates.getX2();
        Double y2 = coordinates.getY2();
        return coordinates;
    }
}

This is the stack trace:
04-Dec-2020 05:53:14.771 SEVERE [http-nio-8080-exec-7] com.sun.jersey.spi.container.ContainerRequest.getEntity A message body reader for Java class model.Coordinates, and Java type class model.Coordinates, and MIME media type application/json was not found.
The registered message body readers compatible with the MIME media type are:
application/json ->
  com.sun.jersey.json.impl.provider.entity.JSONJAXBElementProvider$App
  com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider$App
  com.sun.jersey.json.impl.provider.entity.JSONListElementProvider$App
*/* ->
  com.sun.jersey.core.impl.provider.entity.FormProvider
  com.sun.jersey.core.impl.provider.entity.StringProvider
  com.sun.jersey.core.impl.provider.entity.ByteArrayProvider
  com.sun.jersey.core.impl.provider.entity.FileProvider
  com.sun.jersey.core.impl.provider.entity.InputStreamProvider
  com.sun.jersey.core.impl.provider.entity.DataSourceProvider
  com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$General
  com.sun.jersey.core.impl.provider.entity.ReaderProvider
  com.sun.jersey.core.impl.provider.entity.DocumentProvider
  com.sun.jersey.core.impl.provider.entity.SourceProvider$StreamSourceReader
  com.sun.jersey.core.impl.provider.entity.SourceProvider$SAXSourceReader
  com.sun.jersey.core.impl.provider.entity.SourceProvider$DOMSourceReader
  com.sun.jersey.json.impl.provider.entity.JSONJAXBElementProvider$General
  com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$General
  com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$General
  com.sun.jersey.core.impl.provider.entity.XMLRootObjectProvider$General
  com.sun.jersey.core.impl.provider.entity.EntityHolderReader
  com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider$General
  com.sun.jersey.json.impl.provider.entity.JSONListElementProvider$General

I added every jar file that is needed and now I'm confusing what's wrong!? When I pass an object I get a 415-error and when I pass @QueryParam the parameters are accessible by the postman call not accessible by ajax call though!!!

A: If you want to send JSON, then what you have here is correct
@Path("geo")
public class Geo {

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Coordinates request(Coordinates coordinates){
        Double x1 = coordinates.getX1();
        Double y1 = coordinates.getY1();
        Double x2 = coordinates.getX2();
        Double y2 = coordinates.getY2();
        return coordinates;
    }
}

You have all the Jackson jars. You should remove the POJOMappingFeature in your web.xml and remove the jersey-json jar as this might cause some conflict.
Then add the following in the web.xml
<init-param>
    <param-name>com.sun.jersey.config.property.packages</param-name>
    <param-value>
        example,
        com.fasterxml.jackson.jaxrs.json
    </param-value>
</init-param>

This will tell Jersey to scan the Jackson package for the JSON provider.
Now in your Postman call, do not use the "params" as that will not create JSON. you should use the "body" tab and then manually type in the JSON you want to send
{
  "x1": 1.1,
  "y1": 2.2,
  "x2": 3.3,
  "y2": 4.4
}

Then set the Content-Type header to application/json
After doing all this, it should work. As an aside, I highly suggest you learn to use a dependency manager, either Maven or Gradle. Trying to add jars, you often will miss adding the jars that that jar depends on, which will cause that jar not to work.


text:
Q: In Hakyll, how can I generate a tags page? I'm trying to do something like what's described in this tutorial, i.e., add tags to my Hakyll blog, but instead of generating a page for every tag, just have one page that lists all tags and their posts. So given a Post1 tagged Tag1, and a Post2 tagged Tag1, Tag2, and a Post3 tagged Tag2, my tags.html would look like this:
 Tag1:
  - Post1
  - Post2
 Tag2:
  - Post2
  - Post3

But I'm a Haskell beginner, and I don't fully understand all of Hakyll's monadic contexts. Here's what I have so far:
create ["tags.html"] $ do
    route idRoute
    tags <- buildTags "posts/*" (fromCapture "tags.html")
    compile $
        makeItem ""
            >>= applyTemplate tagListTemplate defaultContext
            >>= applyTemplate defaultTemplate defaultContext
            >>= relativizeUrls
            >>= cleanIndexUrls

The problem is, I don't really know what Tags are, in the context of my blog. I can't seem to print them out for debugging. (I tried adding print tags, but it doesn't work.) So I'm having a really hard time thinking about how to proceed with this.
The complete file is here on GitHub.
Any help is much appreciated.
Update: I'm still not much closer to figuring this out. Here's what I'm trying now:
create ["tags.html"] $ do
        route idRoute
        tags <- buildTags "posts/*" (fromCapture "tags.html#")
        let tagList = tagsMap tags
        compile $ do
            makeItem ""
              >>= applyTemplate tagListTemplate (defaultCtxWithTags tags)

along with:
-- Add tags to default context, for tag listing
defaultCtxWithTags :: Tags -> Context String
defaultCtxWithTags tags = listField "tags" defaultContext (return (tagsMap tags)) `mappend` defaultContext

The full code, as it currently stands, is up here.
Any help with this would be much appreciated. I'm aware of all the documentation, but I can't seem to translate that into working code.

A: I have modified your site.hs to create a rudimentary tags list page which I believe has the structure required: a list of tags, each of which contains a list of posts with that tag.
Here's a summary of each of the things that I had to do to get it to work:
{-# LANGUAGE ViewPatterns #-}

Not strictly necessary, but a nice language extension which I use once. I thought I'd use/mention it since you mentioned that you're a beginner to Haskell, and it's nice to know about.
tags <- buildTags "posts/*" (fromCapture "tags/*.html")

There are two changes needed to this line, compared to the buildTags in your initial site.hs. One is that it should probably moved out of the individual match clauses into the top level Rules monad, so that we can create individual tag pages if required. The other is that the capture was similarly changed from "tags.html#" to "tags/*.html". This is important because Hakyll wants every Item to have a unique Identifier, and not every tags page is the same.
Having the individual tag pages with unique identifiers may not be strictly necessary, but simplifies the rest of the setup since a lot of the Hakyll machinery assumes they exist.  In particular, the Tags: line in the individual post descriptions was not previously being rendered correctly either.
For the same reason, it's a good idea to actually make these individual tag pages routable: without this stanza in the top-level Rules monad, the tags on each post won't render correctly with the default tagsField that you use, since they can't figure out how to link to an individual tag page:
tagsRules tags $ \tag pat -> do
    route idRoute
    compile $ do
        posts <- recentFirst =<< loadAll pat
        let postCtx = postCtxWithTags tags
            postsField = listField "posts" postCtx (pure posts)
            titleField = constField "title" ("Posts tagged \""++tag++"\"")
            indexCtx = postsField <> titleField <> defaultContext
        makeItem "" >>= applyTemplate postListTemplate indexCtx
                    >>= applyTemplate defaultTemplate defaultContext
                    >>= relativizeUrls
                    >>= cleanIndexUrls

Alright, that's the preliminaries. Now onto the main attraction:
defaultCtxWithTags tags = listField "tags" tagsCtx getAllTags         `mappend`
                          defaultContext

Alright, the important thing added here is some tags field. It will contain one item for each thing returned by getAllTags, and the fields on each item will be given by tagsCtx.
  where getAllTags :: Compiler [Item (String, [Identifier])]
        getAllTags = pure . map mkItem $ tagsMap tags
          where mkItem :: (String, [Identifier]) -> Item (String, [Identifier])
                mkItem x@(t, _) = Item (tagsMakeId tags t) x

What's getAllTags doing? Well, it starts with tagsMap tags, just like your example. But Hakyll wants the result to be an Item, so we have to wrap it up using mkItem. What's in an Item other than the body? Just an Identifier, and the Tags object happens to contain a field that tells us how to get this! So mkItem just uses tagsMakeId to get an identifier and wraps up the given body with that identifier.
What about tagsCtx?
        tagsCtx :: Context (String, [Identifier])
        tagsCtx = listFieldWith "posts" postsCtx getPosts             `mappend`
                  metadataField                                       `mappend`
                  urlField "url"                                      `mappend`
                  pathField "path"                                    `mappend`
                  titleField "title"                                  `mappend`
                  missingField

Everything starting with metadataField is just the usual stuff we expect to get from defaultContext; we can't use defaultContext here since it wants to add a bodyField, but the body of this Item isn't a string (but instead a much more useful for us Haskell structure representing a tag).  The interesting bit of this is line which adds the posts field, which should look a bit familiar. The big difference is that it uses listFieldWith instead of listField, which basically means that getPosts gets an extra argument, which is the body of the Item that this field is on. In this case, that's the tag record from tagsMap.
          where getPosts :: Item (String, [Identifier])
                         -> Compiler [Item String]
                getPosts (itemBody -> (_, is)) = mapM load is

getPosts mostly just uses the load function to get ahold of the Item for each post given its Identifier---it's a lot like the loadAll you do to get all the posts on the index page, but it just gives you one post. The weird-looking pattern-match on the left is ViewPatterns in action: it's basically saying that for this pattern to match, the pattern on the right of the -> (i.e. (_, is)) should match the result of applying the function on the left (i.e. itemBody) to the argument.
                postsCtx :: Context String
                postsCtx = postCtxWithTags tags

postsCtx is very simple: just the same postCtxWithTags used everywhere else we render a post.
That's everything necessary to get a Context with everything that you want; all that's left is to actually make a template to render it!
tagListTemplateRaw :: Html
tagListTemplateRaw =
  ul $ do
    "$for(tags)$"
    li ! A.class_ "" $ do
      a ! href "$url$" $ "$title$"
      ul $ do
        "$for(posts)$"
        li ! A.class_ "" $ do
          a ! href "$url$" $ "$title$"
        "$endfor$"
    "$endfor$"

This is just a very simple template that renders nested lists; you could of course do various things to make it fancier/nicer-looking.
I have made a PR to your repo so that you can see these changes in context here.

A: Here is what we've done to achieve this behaviour on our webpage:
Kowainik webpage tags building
And the example of the tag page:
https://kowainik.github.io/tags/haskell
You can ask any questions about the code :)


text:
Q: Problem with c written server displaying a bmp image First off, if anyone would like to compile the server and run it

*

*go to http://pastebin.com/qPnE3jV0

*compile and run it

*go to your browser and type http://localhost:7191/
The function I'm looking at particularly is:
void serveHTML (int socket) {

    char *message;
    int i;
    int j;

    //image data
    char bmpheader[54] = {0x42, 0x4D, 0x5A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x13, 0x0B, 0x00, 0x00, 0x13, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

    char bmpimagedata[36] = {0x07, 0x07, 0xFF, 0x07, 0x07, 0x07, 0x07, 0x07, 0xFF, 0xFF, 0x07, 0x07, 0x07, 0x07, 0x07, 0x66, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0xFF, 0xFF, 0xFF, 0x46, 0x00, 0x00};

   message = "HTTP/1.0 200 OK\r\n"
                "Content-Type: image/bmp\r\n"
                "Content-Length: 90\r\n";
   printf ("%s\n", message);
   write (socket, message, strlen(message));

   // now send the contents of the web page to be displayed
i=0;
j=0;
while (i < 54) {
    printf("%c", bmpheader[i]);
    write (socket, &bmpheader[i], 1);
    i++;
}
while (j < 36) {
    printf("%c", bmpimagedata[j]);
    write (socket, &bmpimagedata[j], 1);
    j++;
}

}

*

*What I've done here is stored the hex
data of a 3x3 bmp file into two
arrays (for convenience of
modification) the header and the
image data. I try to get it to
serve this bmp on a web browser.
However it fails.

*I've placed printf's all over the
place to print what the server is
spitting out... however I think I'm
missing something (possibly a
footer?).
Any help would be appreciated, I'm pulling my hair out as to why it doesn't work.

A: A few points:

*

*Don't use such bizarre code to write out the arrays. Just use plain write(socket, bmpheader, sizeof bmpheader); and the same for the data.

*Inspect the return value of write(); it can fail.

A: Headers need to end with two \r\n - Append \r\n to your message constant.


text:
Q: Qt как связать сигналы между собой Возможно ли прописать в QObject::connect() вызов слота при выполнении условия такого вида:
if (sig1WasSent && sig2WasSent)
    вызов слота

Т.е. мне необходимо вызвать слот, когда были посланы оба сигнала.

A: Что бы не оставался открытым: так делать невозможно


text:
Q: Create custom action in a class for use in Interface Builder I want to create a custom action connection in a class, which should be visible in Interface Builder. For example - I add action / target properties to NSView class just like this:
weak open var object: AnyObject?
open var something: Selector?

The action is something and the target is object.
Now I want in Interface Builder to have 'Send Action' link / connection available for something and to be able to make connection to a @IBAction method to some class (for example the controller of the view), just like it can be done for a simple NSButton. Maybe this is not possible, or maybe I must add some keywords in front of the custom action / target pair, the same way we need to make a property @IBInspectable to appear in Attributes Inspector.
Any help is welcome ;-)

A: I don't think you can do that. You can add @IBInspectable properties to custom NSView subclasses, but there is no selector or action data type for properties. The only allowed types are Boolean, Number, String, Localized String, Point, Size, Rect, Range, Color, Image, Nil.
Interface Builder has hard-wired support for handling the target-action properties of controls.
(BTW you should probably add the Mac OS tag to your quesiton. Most Apple traffic on this board is iOS-related.
EDIT:
As somebody said in a comment, if you're creating an object that has a target/action, it should probably be an NSControl, not an NSView. Controls are the object family that handle target-actions, and there IS a mechanism in Interface Builder for adding target/actions to controls.

A: In iOS, there is one somewhat cheesy option -- you could have an outlet to a UIBarButtonItem, and someone could then drop a standalone UIBarButtonItem in their xib or storyboard.  The UIBarButtonItem can then have the target/action, and your class could then pull the target/action from there in awakeFromNib and assign the values to your own class.   That approach may be replicable in MacOS using NSToolbarItem, but I have not tried.  It's a kludgy option really, as it requires extra xib objects and may not be too obvious what is going on, but it can work.  Basically, the UIBarButtonItem / NSToolbarItem would only be acting as a container for the target/action values.
If you can't subclass NSControl, it would seem the preferred option is to have a delegate, probably.  That is usually fine, unless one controller needs to be the delegate for multiple instances of your class, in which case the delegate methods get more tedious.  Another option is to have your class have a block property, which is performed upon the action, but blocks must be assigned in code and not set up in Interface Builder.


text:
Q: Swift 3.0 Update Annotation on Pin I have an annotation on my pins for my mapView. On my annotation, I have a button and I want to be able to change the button image (from plus to minus) when the user clicks on the button. I am not sure where I can update this. I currently have my button image set up when the user clicks on the pin. The image itself won't update until I reload the map, but I am looking to update the button on the annotation view immediately after the user clicks on it. I am not sure how to update the button while the annotation is popped up.
 func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {

    if let annotation = view.annotation as? MKPointAnnotation {
                let btn = UIButton(type: .detailDisclosure)
                view.rightCalloutAccessoryView = btn
                if annotation.accessibilityValue! == "Minus" {

                    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
                    button.setBackgroundImage(UIImage(named: "minus"), for: .normal)
                    button.addTarget(self, action: #selector(MapVC.minus), for: .touchUpInside)
                    view.leftCalloutAccessoryView = button
                } else {
                    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
                    button.setBackgroundImage(UIImage(named: "plus"), for: .normal)
                    button.addTarget(self, action: #selector(MapVC.plus), for: .touchUpInside)
                    view.leftCalloutAccessoryView = button
                }
    }
}

A: You don't have to use didSelect delegate method. When the user clicks on the button, calloutAccessoryControlTapped delegate method is called. You can change the button image in this delegate method.
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
    if control == view.leftCalloutAccessoryView {
        let button = control as! UIButton
        if annotation.accessibilityValue! == "Minus" {
            button.setBackgroundImage(UIImage(named: "minus"), for: .normal)
        } else {
            button.setBackgroundImage(UIImage(named: "plus"), for: .normal)
        }
    }
}


text:
Q: how to go from using app.config of WCF binding and convert it to bind programmatically in correct manner I have the following binding which works fine when I create client.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="Assets_AssetsPort" closeTimeout="00:01:00" openTimeout="00:01:00"
                    receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
                    bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Mtom" textEncoding="utf-8" transferMode="Buffered"
                    useDefaultWebProxy="true">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <security mode="None">
                        <transport clientCredentialType="None" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="UserName" algorithmSuite="Default" />
                    </security>
                </binding>
                <binding name="AssetsPortBinding" closeTimeout="00:01:00" openTimeout="00:01:00"
                    receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
                    bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                    useDefaultWebProxy="true">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <security mode="None">
                        <transport clientCredentialType="None" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="UserName" algorithmSuite="Default" />
                    </security>
                </binding>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://osi-tm/services/Assets" binding="basicHttpBinding"
                bindingConfiguration="Assets_AssetsPort" contract="InterplayWS.AssetsPortType"
                name="AssetsPort" />
        </client>
    </system.serviceModel>
</configuration>

However now I need to configure this without any config file.  So I attempted to do the following:
    BasicHttpBinding basicBinding = new BasicHttpBinding()
    {
        MaxReceivedMessageSize = 2147483647,
        MaxBufferPoolSize = 2147483647
    };
    basicBinding.MessageEncoding = WSMessageEncoding.Mtom;

    var endpoint = new EndpointAddress(new Uri(String.Format("http://{0}/services/Assets?wsdl", Connection.InterplayHost)));

    var client = new AssetClient(basicBinding, endpoint);

When I run this up I get an error
<Exception>
<ExceptionType>System.ServiceModel.CommunicationException, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>Unrecognized message version.</Message>
<StackTrace>
at System.ServiceModel.Channels.ReceivedMessage.ReadStartEnvelope(XmlDictionaryReader reader)
at System.ServiceModel.Channels.BufferedMessage..ctor(IBufferedMessageData messageData, RecycledMessageState recycledMessageState, Boolean[] understoodHeaders)
at System.ServiceModel.Channels.MtomMessageEncoder.ReadMessage(ArraySegment`1 buffer, BufferManager bufferManager, String contentType)
at System.ServiceModel.Channels.MessageEncoder.ReadMessage(Stream stream, BufferManager bufferManager, Int32 maxBufferSize, String contentType)
at System.ServiceModel.Channels.HttpInput.ReadChunkedBufferedMessage(Stream inputStream)
at System.ServiceModel.Channels.HttpInput.ParseIncomingMessage(Exception& requestException)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at DDMEService.InterplayReference.AssetsPortType.GetChildren(GetChildrenRequest request)
at DDMEService.InterplayReference.AssetsPortTypeClient.DDMEService.InterplayReference.AssetsPortType.GetChildren(GetChildrenRequest request)
at DDMEService.InterplayReference.AssetsPortTypeClient.GetChildren(UserCredentialsType UserCredentials, GetChildrenType GetChildren1)
at DDMEService.Classes.AvidCommand.PopulateGenericAssets(String UNCHostname, String UNCDirectoryPath)
at DDMEService.Classes.CommandManager.PrepareAvidList(String HostName, String DirectoryPath, Boolean SearchSubdirectory, Boolean RenameToDirectory, String FileFilter, String ExtensionFilter, String InterplayHost, String InterplayWorkgroup, String Catalog, String LocatorSequenceStartWords, String LocatorSequenceEndWords, String Username, String Password)
at DDMEService.Classes.CommandManager.Execute()
at DDMEService.ClientHandler.ProcessCommand(String ClientIP, String Command)
at DDMEService.ClientHandler.Process(Object O)
at System.Threading._ThreadPoolWaitCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallbackInternal(_ThreadPoolWaitCallback tpWaitCallBack)
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback(Object state)
</StackTrace>
<ExceptionString>System.ServiceModel.CommunicationException: Unrecognized message version.</ExceptionString>
</Exception>

not working soap request
--uuid:4475db34-2787-4220-b800-15c91678a4be+id=2
Content-ID: <http://tempuri.org/0>
Content-Transfer-Encoding: 8bit
Content-Type: application/xop+xml;charset=utf-8;type="text/xml"

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Header><h:UserCredentials xmlns:h="http://avid.com/interplay/ws/assets/types" xmlns="http://avid.com/interplay/ws/assets/types" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Username>Administrator</Username><Password>avid</Password></h:UserCredentials><ActivityId CorrelationId="f29e64f8-1568-4683-b196-d53bd97a2cec" xmlns="http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics">13063b98-becc-416a-89ec-23a23498ed21</ActivityId></s:Header><s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><GetChildren xmlns="http://avid.com/interplay/ws/assets/types"><InterplayURI>interplay://A51WG6/Catalogs/000</InterplayURI></GetChildren></s:Body></s:Envelope>
--uuid:4475db34-2787-4220-b800-15c91678a4be+id=2--

working soap request
--uuid:f1481ad5-def1-42bf-a3ca-f9cff5eb856b+id=2
Content-ID: <http://tempuri.org/0>
Content-Transfer-Encoding: 8bit
Content-Type: application/xop+xml;charset=utf-8;type="text/xml"

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Header><h:UserCredentials xmlns:h="http://avid.com/interplay/ws/assets/types" xmlns="http://avid.com/interplay/ws/assets/types" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Username>Administrator</Username><Password>avid</Password></h:UserCredentials></s:Header><s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><GetChildren xmlns="http://avid.com/interplay/ws/assets/types"><InterplayURI>interplay://WG5C/Catalogs/Sundance</InterplayURI></GetChildren></s:Body></s:Envelope>
--uuid:f1481ad5-def1-42bf-a3ca-f9cff5eb856b+id=2--

How can I properly form this to make this work against my service?

A: why do you create the elements and then push the mtom? you already have a text encoder there so the mtom would be a second encoder. use this instead:
basicBinding.messageEncoding = WSMessageEncoding.Mtom

A: I had to remove ?wsdl from http://{0}/services/Assets?wsdl

A: To create an equivalent binding in code you just need to set the properties on your BasicHttpBinding instance to the values specified in your config file.
From a quick scan through your code it looks like you can remove the code that creates the MtomMessageEncodingBindingElement instance and set the MessageEncoding property on basicBinding to Mtom.


text:
Q: How to explicitly clear cookies using WWW::Scripter module in perl? Simple perl code is:
      use WWW::Scripter;

      ...

      my $w = WWW::Scripter->new('agent' => 'myAgent');
      $w->use_plugin('JavaScript');

      ...

      $w->get($url);

      ### WWW::Mechanize automatic cookies = good for now

      $w->add_header(Referer => $url);
      $url = $w->document->getElementsByTagName('a')->[0]->href;
      $w->get($url);

      ...

      ### WWW::Mechanize automatic cookies = NOT good for now
      ### ! need to clear cookie jar here !

      ...

      $w->add_header(Referer => $url);
      $url = $w->document->getElementsByTagName('a')->[0]->href;
      $w->get($url);

One of good feature of WWW::Mechanize is automatic cookies, which is good at some point, but sometimes cookies need to be cleared. How?

A: The WWW::Mechanize method cookie_jar returns a HTTP::Cookies object. The relevant method is indeed named clear.

A: Looking at the documentation, can't you just reset the cookie jar attribute?
e.g.
$w->cookie_jar({});