text:
Q: Need to zero a formula field for group in Crystal Reports IX I am generating a margin percent in a report using CR IX.  The detail percentages work just fine but the subtotal by product code does not.  It always shows the same percentage regardless of the data that is pulled from the database.  The values I'm getting are these 32.87 and 67.13, no matter if the cost and margin are zero.
What I would like to do is in the group header zero out these two percentage fields.  I have the following in the suppress formula:
WhilePrintingRecords;{@SumMarginpct}= 0;{@SumTCpct}= 0;

but this has not worked.  The percent formula fields are the following:
Sum ({@total_cost}) / Sum ({@ext_disc_price}) * 100 ( for the SumTCpct field)
Sum ({@margin}) / Sum ({@ext_disc_price}) * 100     ( for the SumMarginpct field)

I am not a CR programmer, mostly sql and python so the nuisances of CR are not readily available :)
Appreciate any help I can get.
Thanks
@Craig
I have modified the formulas some based on reading a reference book and a web tutorial:
if Sum ({@total_cost}, {Rpt_MarginByProductCodeSp;1.product_code}) = 0
then 0
else
Sum ({@ext_disc_price}, {Rpt_MarginByProductCodeSp;1.product_code}) %
Sum ({@total_cost}, {Rpt_MarginByProductCodeSp;1.product_code})

this is one of the formulas, the other is just like to only it uses the Sum {@margin} field.

A: Place these formula fields in the product-code group's footer:
// {@SumTCpct}
Sum ({@total_cost}, {table.product code}) / Sum ({@ext_disc_price}, {table.product code}) * 100

// {@SumMarginpct}
Sum ({@margin}, {table.product code}) / Sum ({@ext_disc_price}, {table.product code}) * 100


text:
Q: How to build chromium's sandbox only? How can I use the chromium's sandbox as static lib? And I want to build its sandbox only instead of the whole browser to learn how sandbox works. Any help?
I learned this blog, but seems out of time.
Using the Google Chrome Sandbox

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to replace simplify code when calling command bar combobox I have this code in a class module
Public WithEvents evtHandler As VBIDE.CommandBarEvents

Private Sub evtHandler_Click(ByVal CommandBarControl As Object, _
    handled As Boolean, CancelDefault As Boolean)

    On Error Resume Next
    Application.Run CommandBarControl.OnAction

    handled = True
    CancelDefault = True
End Sub

I have this code in a module
Sub CommandBarComboBox_Create()
    Dim cmdBar As commandBar: Set cmdBar = Application.VBE.CommandBars("Custom")
    Dim arr As Variant: arr = Array("item_1", "item_2", "item_3")

    Dim i As Byte
    Dim newCtrl As CommandBarControl: Set newCtrl = cmdBar.Controls.Add(msoControlComboBox)

    With newCtrl
        .caption = "myList"
        For i = LBound(arr) To UBound(arr)
            .AddItem arr(i), i + 1
        Next i
        .OnAction = "'processSelection'"
        .tag = "myTag"
    End With

    ' Create event handler
    Set MenuEvent = New VBE_cmdHandler
    Set MenuEvent.evtHandler = Application.VBE.Events.CommandBarEvents(newCtrl)
    EventHandlers.Add MenuEvent
End Sub

Sub processSelection()
    Dim cmdBar As commandBar: Set cmdBar = Application.VBE.CommandBars("Custom")
    Dim userChoice As Long: userChoice = cmdBar.Controls(2).ListIndex

    Select Case userChoice
        Case 1
            Debug.Print "OPTION 1"
        Case 2
            Debug.Print "OPTION 2"
        Case Else
            Debug.Print "OPTION 3"
    End Select
End Sub

This works just fine but I would like to change it, so when sub processSelection is called, it implicit knows the calling control, so I don't have to specify it.
How can it be done?
Regards
Elio Fernandes

A: I just found a way to solve my problem, using the tag property of the control.
I replaced the first 2 lines of code of the sub processSelecion with 3 new lines, but without the need to identify with command bar and which control was last used.
With tag property, I can find which control was last used and consequently which ListIndex item was selected by the user.
Sub processSelection()
    Dim curTag$: curTag = Application.VBE.CommandBars.ActionControl.tag
    Dim myControls As Object: Set myControls = Application.VBE.CommandBars.FindControls(tag:=curTag$)
    Dim userChoice As Long: userChoice = myControls.item(1).ListIndex

    Select Case userChoice
        Case 1
            Debug.Print "OPTION 1"
        Case 2
            Debug.Print "OPTION 2"
        Case 3
            Debug.Print "OPTION 3"
        Case Else
            Debug.Print "OTHER"
    End Select
End Sub


text:
Q: Lost Dogmeat in fallout 4 I ran into an issue today. I was with nick valentine on the Kelloggs mission when we came across some super mutants. I tried to fight them off but they were too strong, so I hid in a nearby shed. Nick followed me but dogmeat didn't. Once I regened health I went back out to fight them. But they were already dead. (Dogmeat must of killed them.) But I couldn't find dogmeat. I searched for quite a while before giving up. So I then went to Google and someone said to try: prid 1d162 and then recycleactor then I checked red rocket and saw him there. But when I tried to do anything it showed the "Press E to talk" message so I did. I said something like "We're gonna need you to find Kellogg." And he won't follow me or anything. He's stuck on the Kelloggs mission or something. Any ideas?

A: Based on personal recollection and this guide, Dogmeat will lead you to where Kellogg is, but you must follow him. If you stray from the quest, Dogmeat will not follow you. He will not be available as a usual follower until you make it into Kellogg's hideout.
I had a similar issue where I made it to the hideout but didn't bother to go in and I couldn't use Dogmeat until I continued the quest.
For reference, Dogmeat will lead you to

 Fort Hagen


text:
Q: When parsing text for n-grams - should punctuation be included? I want to start working on data-mining by parsing text. It seems like the best place to start is by processing n-grams out of text to try sentiment analysis.
Muffins are fine, I wouldn't say I like them though.

However, I'm curious to know if I should include punctuation or not. (I plan on starting with 3-grams and working up since I'm not sure 2-grams include enough information for accurate results.)
Muffins are fine | are fine [,] | I wouldn't say | ....

Since a "," was found, start over at next word after the ",". Instead of including the punctuation like normal.
Muffins are fine | are fine , | fine , I | , I wouldn't | ...

Can anyone tell me if this is a bad idea?

A: Here's a hint: Google doesn't include punctuation in n-grams.

A: Google ignores punctuation, but there are non-alphanumeric characters that are not ignored.
For example, search these word/phrases:

*

*tech spec

*tech-spec

*tech,spec

*tech_spec

The search results vary, showing Google does consider some characters significant.
Also, are you doing this in non-English languages?
If so, then consider creating n-grams from a certain number of characters, instead of words. This will lead to better results on many non-English languages, and it's the only way to effectively parse CJK-type languages that don't use significant whitespace.


text:
Q: Using Log4Net in PowerShell I am looking for a clear example of using Log4Net in PowerShell to write a local log file.  I have googled it, but the examples I have found (and linked to) have been confusing to me.  I would love to include a specific problem, but since I am looking for a good reference I can't.
Edit:  Rewritten for clarity… maybe?

A: Well, seems like I worded my question poorly.
I kept finding this link powershell-logging-using-apache-log4net but found it really hard to read.
So, I took this code and wrote it in friendlier fashion (for me).  The entire ColoredConsoleAppender part can be removed, as it is just for displaying to console.
#####################################################################################################################
#Load log4net.dll
$DllPath = ([System.IO.Directory]::GetParent($MyInvocation.MyCommand.Path)).FullName
$DllFile = Resolve-Path (Join-Path -Path $DllPath -ChildPath 'log4net.dll')
[Void][Reflection.Assembly]::LoadFile($DllFile)
#####################################################################################################################
#FileAppender
#
#Define Values for FileAppender Configuration
$Pattern = '[%date{yyyy-MM-dd HH:mm:ss.fff} (%utcdate{yyyy-MM-dd HH:mm:ss.fff})] [%level] [%message]%n'
$PatternLayout = [log4net.Layout.ILayout](new-object log4net.Layout.PatternLayout($Pattern))

$LogPath = ([System.IO.Directory]::GetParent($MyInvocation.MyCommand.Path)).FullName
$LogFile = Join-Path -Path $LogPath -ChildPath $('LogFile_{0:yyyy-MM-dd}_{0:HH-mm-ss}.log' -f (Get-Date))

$AppendToFile = $True

#Load FileAppender Configuration
$FileAppender = new-object log4net.Appender.FileAppender($PatternLayout,$LogFile,$AppendToFile);
$FileAppender.Threshold = [log4net.Core.Level]::All
[log4net.Config.BasicConfigurator]::Configure($FileAppender)
#####################################################################################################################
#ColoredConsoleAppender
#
#Define Values for ColoredConsoleAppender Configuration
$Pattern = '[%date{yyyy-MM-dd HH:mm:ss.fff}] %message%n'
$PatternLayout = [log4net.Layout.ILayout](new-object log4net.Layout.PatternLayout($Pattern))
$ColoredConsoleAppender = new-object log4net.Appender.ColoredConsoleAppender($PatternLayout)

$ColoredConsoleAppenderLevelAndColors = new-object log4net.Appender.ColoredConsoleAppender+LevelColors

$ColoredConsoleAppenderLevelAndColors.Level = [log4net.Core.Level]::Debug
$ColoredConsoleAppenderLevelAndColors.ForeColor = [log4net.Appender.ColoredConsoleAppender+Colors]::Green
$ColoredConsoleAppender.AddMapping($ColoredConsoleAppenderLevelAndColors)

$ColoredConsoleAppenderLevelAndColors.level = [log4net.Core.Level]::Info
$ColoredConsoleAppenderLevelAndColors.ForeColor = [log4net.Appender.ColoredConsoleAppender+Colors]::White
$ColoredConsoleAppender.AddMapping($ColoredConsoleAppenderLevelAndColors)

$ColoredConsoleAppenderLevelAndColors.level=[log4net.Core.Level]::Warn
$ColoredConsoleAppenderLevelAndColors.ForeColor=[log4net.Appender.ColoredConsoleAppender+Colors]::Yellow
$ColoredConsoleAppender.AddMapping($ColoredConsoleAppenderLevelAndColors)

$ColoredConsoleAppenderLevelAndColors.level=[log4net.Core.Level]::Error
$ColoredConsoleAppenderLevelAndColors.ForeColor=[log4net.Appender.ColoredConsoleAppender+Colors]::Red
$ColoredConsoleAppender.AddMapping($ColoredConsoleAppenderLevelAndColors)

$ColoredConsoleAppenderLevelAndColors.level=[log4net.Core.Level]::Fatal
$ColoredConsoleAppenderLevelAndColors.ForeColor=[log4net.Appender.ColoredConsoleAppender+Colors]::HighIntensity -bxor [log4net.Appender.ColoredConsoleAppender+Colors]::Red
$ColoredConsoleAppender.AddMapping($ColoredConsoleAppenderLevelAndColors)

$ColoredConsoleAppender.ActivateOptions()

#Load FileAppender Configuration
$ColoredConsoleAppender.Threshold = [log4net.Core.Level]::All
[log4net.Config.BasicConfigurator]::Configure($ColoredConsoleAppender)
#####################################################################################################################
$Log = [log4net.LogManager]::GetLogger("root")
$Log.Debug('Debug message.')
$Log.Info('Info message.')
$Log.Warn('Warn message.')
$Log.Error('Error message.')
$Log.Fatal('Fatal message.')
[log4net.LogManager]::ResetConfiguration()


text:
Q: Merge and Combine Hash Values in an Array I'm building an array where I need to combine or merge all of the file paths in a hash with two values inside.
The input hash looks like this:
h = { "Apple_HLS(Media)"=>[
        "\\\\workspace1\\test-media.m3u8",
        "\\\\workspace1\\OTT-1\\segment_1.ts"
      ],
      "Apple_HLS_Prev(Media)"=>[
        "\\\\workspace1\\test-media-p.m3u8",
        "\\\\workspace1\\OTT-3\\test-media-p.m3u8"
      ]
    }

I tried this code:
outputs['output_files'] =
  inputs['output_files_hash'].
  select{ |k,v| k == 'Apple_HLS(Media)' }.
  values

And it works with only one value in the hash, which yields the file paths inside "Apple_HLS" value.
[["\\\\workspace1\\test-media.m3u8",
  "\\\\workspace1\\OTT-1\\segment_1.ts"]]

But I need to combine and merge the values of "Apple_HLS_Prev" and include it in the array output. I tried this code and it didn't merge the values, instead it shows blank.
EDIT: I was expecting a merged and combined output of the array like this:
[["\\\\workspace1\\test-media.m3u8",
  "\\\\workspace1\\OTT-1\\segment_1.ts",
  "\\\\workspace1\\test-media-p.m3u8",
  "\\\\workspace1\\OTT-3\\test-media-p.m3u8"]]

Hope you can answer. Thanks guys!

A: As others have commented,  you need to show what you actually expect your output to be but I think I understand what you are looking for.
Here is a hash that I think matches the format of your hash.
my_hash = {key1: [:key1_value1, :key1_value2],key2: [:key2_value1, :key2_value2], key3: [:key3_value1, :key3_value2]}

To merge all the values just get the values,  which will be a array of 2 element arrays,  and then flatten that in to an single array.
my_hash.values.flatten

returns:
[:key1_value1, :key1_value2, :key2_value1, :key2_value2, :key3_value1, :key3_value2]

If you want to retain the value pairs, then just don't flatten the values.
my_hash.values

returns:
[[:key1_value1, :key1_value2], [:key2_value1, :key2_value2], [:key3_value1, :key3_value2]]

If you only want to select a subset of the entries in your has you can do something like this:
my_hash.select {|k,v| [:key1, :key2].include? k}.values.flatten

which returns:
[:key1_value1, :key1_value2, :key2_value1, :key2_value2]

The reason the following did not work is because as you saw the first select only returns the entry matching 'Apple_HLS(Media)' the second select is applied to the result of the first select which no longer includes the entry for 'Apple_HLS_Prev(Media)'
outputs['output_files'] = inputs['output_files_hash'].select{ |k,v| k == 'Apple_HLS(Media)' }.select{ |k,v| k == 'Apple_HLS_Prev(Media)' }.values

While I think what I posted (using the array include? method) above is cleaner, you might get what you want by saying the key should be Apple_HLS(Media) OR Apple_HLS_Prev(Media)
outputs['output_files'] = inputs['output_files_hash'].select{ |k,v| k == 'Apple_HLS(Media)' || k == 'Apple_HLS_Prev(Media)'}.values

but I think this is cleaner:
outputs['output_files'] = inputs['output_files_hash'].select { |k,v| ['Apple_HLS(Media)', 'Apple_HLS_Prev(Media)'].include? k }.values

A: h = { "Apple_HLS(Media)"=>[
        "\\\\workspace1\\test-media.m3u8",
        "\\\\workspace1\\OTT-1\\segment_1.ts"
      ],
      "Apple_HLS_Prev(Media)"=>[
        "\\\\workspace1\\test-media-p.m3u8",
        "\\\\workspace1\\OTT-3\\test-media-p.m3u8"
      ]
    }

[h.map {|k, v| v }.flatten]
#=> [["\\\\workspace1\\test-media.m3u8", "\\\\workspace1\\OTT-1\\segment_1.ts", "\\\\workspace1\\test-media-p.m3u8", "\\\\workspace1\\OTT-3\\test-media-p.m3u8"]]


text:
Q: Generating a code coverage report with PHPUnit Does anyone know the correct command line to generate a code coverage file on a PHP project? I've already installed the XDebug tool.
In the official documentation from PHPUnit, I found the following command line, but it is not working:
phpunit --coverage-text=<file>

where  is the file where output is going to be stored.
I don't have any tests yet, but is there a way to generate a report file, even though there are no tests in the project?

A: You'll need to include the path to your tests, as well as the white list command with the path to the source code to be tested. E.g.
phpunit --coverage-text="coverage.txt" ./path/to/tests --whitelist="./path/to/code"

Where coverage.txt is the file that the output will be stored in. You can generate a report without any tests.


text:
Q: How to get strings that contain only capital letters that exists between any character and space I want to extract only uppercase characters  from a string which i tried in php and got the result but I  want get working on javascript. I tried it in Rublar and I am sharing the link below with example.
http://rubular.com/r/zNcSuNY94y
This is the regular expression that i used for getting the output
/(\b[A-Z]{2,}\b)/x

For example if we enter
gdgdg $HHH $Hhh AAAA $%%% $88 $hHH $HH $YY $YUN

we must get
HHH HH YY YUN

as a result

A: The following will work fine in JavaScript:
"$AAA dflkdklfg sdkjfhgdjkfg #JFJJJJ $SSjsfdsd YYYYYY".match(/(\b[A-Z]{2,}\b)/g);
>> ["AAA", "JFJJJJ", "YYYYYY"]

Note, that JS doesn't have x flag in regex. You should use g flag to match all occurrences.

A: (\${1}[A-Z]{2,}\b)

Using the above code will give the right answer


text:
Q: How to return the value after volley response Android I am new to volley in Android. I tried to collect data from database via volley request. However, the program continue proceed before the value come in. Anyone has solutions regard this issue? I have used break point to check the sequence of the program. It will run return categoryList in DatabaseCategory before the onSuccess function been called.
This is the class to call DatabaseCategory
public class DatabaseFacade implements Database {

private DatabaseCategory databaseCategory;

public DatabaseFacade(Context context) {
    databaseCategory = new DatabaseCategory(context);
}

@Override
public List<Category> readCategory() {
    return (List<Category>) databaseCategory.loadData(DatabaseUrl.getCategoryReadUrl(), null);
}

}
This is the class to load the data
public class DatabaseCategory extends DatabaseAbstract{

private Context context;
private List<?> categoryList;

public DatabaseCategory(Context context) {
    this.context = context;
}

@Override
public List<?> loadData(String url, Object object) {
    databaseLoad = new DatabaseLoad(context, ObjectType.CATEGORY, url);
    databaseLoad.execute(new CallBack() {
        @Override
        public void onSuccess(List<?> list) {
            categoryList = list;
        }

        @Override
        public void onFail(String msg) {
            // Do Stuff
        }
    });
    return categoryList;
}

This is the class to process volley request
public class DatabaseLoad {

private static final String FAIL_MESSAGE = "Some error occur. Please try later.";
private static final String STATUS_CODE = "success";
private static final int SUCCESS = 1;
private Context context;
private ObjectType objectType;
private String url;
private JSONObject json;
private List<?> loadList;

public DatabaseLoad(Context context, ObjectType type, String url) {
    this.context = context;
    this.objectType = type;
    this.url = url;
}

public void execute(final CallBack onCallBack) {

    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {

                    JSONObject obj;
                    try {
                        obj = new JSONObject(s);
                        if(obj.getInt(STATUS_CODE)==SUCCESS){
                            Log.d("logindatabase","success");
                            switch (objectType) {
                                case CATEGORY:
                                    loadList = loadCategory(obj);
                                    break;

                                default:
                                    break;
                            }
                            onCallBack.onSuccess(loadList);
                        }else{
                            Log.d("logindatabase","fail");
                            Toast.makeText(context, FAIL_MESSAGE , Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(context, FAIL_MESSAGE , Toast.LENGTH_LONG).show();
                        onCallBack.onFail(e.toString());
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {

                    //Showing toast
                    Toast.makeText(context, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            //Creating parameters
            Map<String,String> params;
            //Adding parameters
            switch (objectType) {
                case CATEGORY:
                    params = loadCategoryParameter();
                    break;

                default:
                    params = new Hashtable<String, String>();
                    break;
            }

            //returning parameters
            return params;
        }
    };

    //Creating a Request Queue
    RequestQueue requestQueue = Volley.newRequestQueue(context.getApplicationContext());

    //Adding request to the queue
    requestQueue.add(stringRequest);

}

private Map<String,String> loadCategoryParameter() {
    Map<String,String> params = new Hashtable<String, String>();
    return params;
}

private List<Category> loadCategory(JSONObject obj) throws JSONException {
    List<Category> categoryList = new ArrayList<>();
    JSONArray categoryArray ;
    categoryArray = obj.getJSONArray("posts");

    for (int i = 0; i < categoryArray.length(); i++) {
        JSONObject c = categoryArray.getJSONObject(i);
        int id = c.getInt("id");
        String name = c.getString("name");
        String type = c.getString("type");
        String image = c.getString("image");
        Category category = new Category(id,name,type,"",image);
        categoryList.add(category);
    }
    //Log.d("categorylist",obj.toString());
    return categoryList;
}
}


text:
Q: Spring boot rest api returns 404 I have my main class like this:
package com.ratings.main;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
    public static void main( String[] args ) {
        SpringApplication.run(App.class, args);
        System.out.println( "Hello World!" );
    }
}

package com.ratings.controller;
@RestController
public class PollController {

    @Autowired
    Poll poll;

    @GetMapping("/")
    public String home() {
        System.out.println("home " + "HOME");
        return "Home";
    }
}

And pom.xml file:
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.ratings.main.App</groupId>
  <artifactId>Ratings</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>Ratings</name>
  <url>http://maven.apache.org</url>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.5.RELEASE</version>
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>repackage</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <mainClass>com.ratings.main.App</mainClass>
          <excludeDevtools>false</excludeDevtools>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>

When I try http://localhost:9090/ I get 404. Why is it not return string "Home"?

A: Your SpringBootApplication class is in the package:
package com.ratings.main;

And your controller in
package com.ratings.controller;

The controller must be in the same or below the SpringBootApplication.
So either move your SpringBootApplication to
com.ratings

or move the controller to
com.ratings.main.controller

A: put your controller class in this package com.ratings.main.
@SpringApplication contains @ComponentScan. this annotation scans your beans and configurations from your main package and its subgroup.

A: @SpringBootApplication package: com.ratings.main;
@Controller package:  com.ratings.controller;
The controller class must be in the same or below the main class which is annotated with @SpringBootApplication. You can solve this with adding example package like this ;
com.ratings.main.*;  same order or below.
On the other hand you can use @ComponentScan for your controller packages.
@ComponentScan(value = {"your.controller.package"})

@SpringBootApplication already has this tag but it's scanning only same order and below.


text:
Q: Is the PCI-E x1 slot of this motherboard faulty? As you may know, GPU risers are composed of two PCBs, one to be connected to a PCI-E slot on motherboard, and the other one has a PCI-E x16 slot for the graphics card. When I insert  the former PCB in a PCI-E x1 slot on this 10+ years old motherboard, there is some short circuit, and consequently, two traces on the PCB are burned. Then if I insert that damaged PCB in a PCI-E x16 slot on the motherboard, the graphics card works properly, with no problem that I can observe. This has happened with two different GPU risers, so I guess riser isn't the cultprit. By the way, the motherboard has only one PCI-E x1 slot.
How can I test if the motherboard or the graphics card is faulty without damaging other PCBs? And why does the damaged PCB work on a PCI-E x16 slot?


text:
Q: Validating more that one email field Im using Joren Rapini's validation code to for my online form. Joren's Website
It allows you to check to see if an email address has been correctly entered, but I have 2 email addresses that I want to validate in the form.
Any idea how I would do this?
I've tried adding in email = $("#youremail"); as well as the one that's currently in the code which is email = $("#receiveremail"); but it only works for one.
$(document).ready(function(){
    // Place ID's of all required fields here.
    required = ["youremail", "name", "receiveremail", "message"];

    // If using an ID other than #email or #error then replace it here
    email = $("#receiveremail");
    errornotice = $("#error");

    // The text to show up within a field when it is incorrect
    emptyerror = "Please fill out this field";
    emailerror = "Not a vaild email";
});

A: He doesn't do a great job of explaining this, but it's fairly straightforward.  You have to validate two separate email fields:
if (!/^S+@S+.S+$/.test(email.val())) {
    email.addClass("needsfilled");
    email.val(emailerror);
}
var email2 = $("#youremail");
if (!/^S+@S+.S+$/.test(email2.val()) {

Of course it would be better to loop over the emails in a similar setup to how required is done.
Use var too.

A: You need to run the validation code for your other field
in document.ready
otheremail = $("#otheremail");

in form submit
if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(otheremail .val())) {
            otheremail .addClass("needsfilled");
            otheremail .val(emailerror);
        }

No offense to Joren Rapini but this code is hacky and shouldn't be used for other than the smallest purpose.


text:
Q: Deleting all C comments with sed I am trying to write a script that will delete all comments and everything in between inside C files in my current directory. I've been using sed, and this is what I have so far:
sed -i '/ * [^()] */d' *.c
This works when the comments are on the same line as an asterisk or backslash.
However it doesn't work when there is a commented line without a slash or asterisk.
I know sed goes line by line, I just don't know how to tell it to keep deleting until it sees a */.

A: Removing comments without using a real C-preprocessor is not exactly trivial. I once came up with something like this:
perl -0777 -pe'
 s{
     /\*.*?\*/
   | //[^\n]*
   | (
        "(?:\\.|.)*?"
      | '\''(?:\\.)?.*?'\''
      | \?\?'\''
      | .[^'\''"/]*
     )
  }{if ($1eq""){" "}else{$1}}exsg'

Which should cover most cases like things like:
printf("%c%c%s", '"' /* d-quote */, '\'', "/*" "*/");

See the interesting discussion there for more details.

A: If this doesn't have to be done in sed, then you can do it easily with perl:
perl -p0i -e 's#/\*.*?\*/##sg' *.c

Note that this will delete parts of quoted strings that are not meant to be comments at all as in the example in the comments below.


text:
Q: How to mock a class method's which is initialized inside another class in typescript using ts mockito? This is my Class I want to test using mocha-chai test framework in typescript.
I am using ts-mockito for mocking.
export class ClassA implements IClassA {

    private classAResource: IClassAResource;

    constructor(){
         this.classAResource= new ClassAResource();
    }

    public async cancel(jobid){
       const job = this.classAResource.getJob(jobid);
       //cancel logic
    }
}

ClassAResource class looks like this,
export class StreamResource implements IStreamResource {

private jobs: Map<string, Job>;

 constructor(){
 this.jobs= new Map();
 }

public async createJob(): Promise<Job> {
//add the job to map
}

public async getJob(jobid): Promise<Job>{
//return the specified job item from map
}

}

In my test I try to mock ClassAResource's getJob method like this,
const classAResource: IClassAResource = new ClassAResource ();
 const classAResourceSpy = spy(classAResource);

 when(classAResourceSpy.getJob(anyString())).thenResolve(job);

And I call the ClassA cancel method like this,
classA.cancel(jobid)

I expect the getJob call in cancel method to be mocked and return a job object.
But the test is not behaving according to my expectation. Mock doesnt come into picture and getJob() goes to actual implementation and return undefined.
I read online, this issue is because of the constructor initializations in ClassAResource class.
I removed the constructor and tried and now the getJob mock works.
But I need the constructor to instantiate the map object and ability to maintain the jobs.
Is there some workaround through which I can mock getJob() with constructor in place?
Am I doing something wrong here?
I am kind of relatively new to typescript and ts-mockito and any help is greatly appreciated.

A: This really has nothing to do with TypeScript specifically, but rather a testability issue due to breaking the Dependency Inversion principle.
Instantiating members in the constructor of the class causes a testability issue, since the control over the instantiation is in the hands of the code under test (a.k.a "unit under test", "class under test", etc.). That means, that you have little to no control over which instance the class you're testing will have.
There are some mocking libraries that allow a "hostile takeover" of the instantiation of certain classes (at least for Java, see PowerMock), but they should be used very sparingly, if at all, since they contribute to perpetuating the lack of testability.
Instead of instantiating IClassAResource from the constructor of ClassA, you should either get the instance via injection (DI, constructor, setter method, etc.), or at least use a factory/builder. This way your class would become testable and your design will be improved.
In general, you should adhere to all of the SOLID principles, since they are, at least at the moment, considered the most accurate and concise set of good OOP design principles.


text:
Q: How to call a method when a select box is initialized in an Angular app I have used a select box inside a row. The row is generated using a loop. I need to call a method when this select box is
initialized. This method will pass the dynamically generated row data as an argument.
I am confused as to how this can be achieved in Angular4/5.
In AngularJS it could be done like this:
<tr ng-repeat="row in myData track by $index">
  <select class="form-control" ng-model="row.val" ng-init="methodToCall(row)">
</tr>

A: I might use my own component for that purpose:
So create new component as follow:
import {Component, onInit, Input} from "@angular/core";

@Component({
     selector: "custom-select"
 })
export class customeSelect implements onInit{
      @Input() row:any;
      ngOnInit(){
         //You can call what ever you want after your component initialized.
         console.log(this.row);
      }
}

and use it in your ngfor like below:
<tr *ngFor="row in myData">
    <custom-select [row]="row"></custom-select>
</tr>


text:
Q: How to see working changes on vscode source control Really keen to find out if there is a way to compare an editable panel on vscode to what is on another git branch i.e. what the diff is locally to that on origin master / another branch... but not in 'read-only' mode.
Ideally on the source control extension, under branches i would like to see a list of changed files and click on them, to open two panels one with the branch i select and one with working changes / editable.
Any idea how to do this? I am sure i used to be able to do it. Thank you.

A: Repositories view of git lens in the source control extension.... hidden by default.... check setting of gitlens in vscode. Branches etc won't show working changes, but repositories view does...


text:
Q: JSON difference between { myParameter : 77 } and { 'myParameter' : 77 } I have several AJAX calls to web services in an ASP.Net application, basically I am using JQuery to make the calls but I would like to know the difference (if any) between writing:
data: "{ 'myParameter' : 77 }"

and
data: "{ myParameter : 77 }"

I have tried both approaches and they work so what's the difference?
Edit 1
Ok so according to my understanding, they are valid because they are valid in JavaScript but they are not strictly JSON valid objects, so what's the best practice or the recommended use?

A: Neither of them are actually valid JSON (which requires that all key names are double-quoted with "), but there is really no difference between the three when parsing them in JavaScript, because all three (single quotes, double quotes, and no quotes) are valid in JavaScript object literals.
The actual difference comes when you need key names that aren't valid identifiers in JavaScript; for example, "key-name". {"key-name": 5} would work, but {key-name: 5} would not.


text:
Q: Access is denied in windows cmd.Why? a.txt and b.txt are text files and in_red.exe is a program that takes in input as characters and outputs characters till EOF is reached.I am the admin of the system.
Also,windows gives a popup saying this app isin't available in your PC.
    C:\Users\Aryamaan Jain\Desktop\io_redir>dir /b
    a.txt
    b.txt
    in_red.exe

    C:\Users\Aryamaan Jain\Desktop\io_redir>in_red.exe < a.txt >b.txt
    Access is denied.

A: After a long search,I found out that the program in_red.exe got corrupted(became of size 0kb) for some reason I don't know. However, I replaced the program and now the command is working perfectly.

A: Access is denied as you are not the owner of the folder where you are trying to execute the command. To get ownership of the folder please follow the following steps:

*

*Right click folder

*Select "Properties"

*Select the "Security" tab

*Click the "Advanced" button

*Select the "Owner" tab

*Click the "Edit" button

*Under 'Change owner to' highlight the user you wish to set as owner

*Check the 'Replace owner on subcontainers and objects' box

*Click the 'Apply' button

A: Run it as administrator to prevent Google showing a snap error:
REG ADD "HKLM\Software\Policies\Google\Chrome" /v RendererCodeIntegrityEnabled /t REG_DWORD /d 0

A: Look at the following issues

*

*You have a personal firewall installed. Try uninstalling it.

*You have not logged in as an administrator, try to login as an administrator.

*You can also check by right clicking c:\windows\system32 folder or c:\windows\system32\ipconfig.exe and selecting Properties. Click on the security tab and check for the permission for users. Make sure that the Read & Execute permission is on.

*If the above steps don't work, you can right click on C: (the OS partition), add your account and replace permissions of all the child objects.


text:
Q: Windows 10 x64 very poor performance and heavy IO usage After a clean install of windows 10 it was very unstable and poor performance, to open Explorer for example took ~10 secs and it freeze/unfreezing constantly.
And I've observed a heavy disk IO.
What's the probable problem and solution ?

A: After a lot of searching and tries I've found the problem.
The problem in that case was the Sata Mode that was set to IDE, after setting it to AHCI and booted in safe mode (to install de AHCI drivers) the windows is now smoothly.


text:
Q: Is it possible to force knifes only for the first round? Is it possible to configure a CS:GO server so that in the first round everyone is is forced to use knifes only (no pistols)?
If so, how?

A: The only way this is possible would be to use a plugin. Plugins can modify what is and isn't allowed on servers, so, for example, you could have someone freeze in their spot if they equip a gun on round one.
However, most likely nobody made a plugin for what you want yet, but if you make an account on these forums, and request a plugin, hopefully somebody can make a plugin suiting your needs.


text:
Q: Ajax return automatic ordering number named arrays So, i have a problem where my javascript is auto ordering number named arrays.
My object comes from an Ajax call, so i cant build it differently.
Example of my problem:
var test = {"1": "test1", "0": "test2", "2": "test3"}

output
console.log(test);

// {0: "teste2", 1: "teste1", 2: "teste3"}

The order should be 1,0,2...
Any way to solve this?
Btw, this is an example, in the script i am getting an object throw ajax and when i console.log it, it orders automatic, so map() functions wouldn't work here.

A: Key order is not always guaranteed with objects. The default order of properties when printing an object are as follows:

*

*Integer-like keys in ascending order

*String keys in insertion order

*Symbols in insertion order

In your example, below, the integer-like keys are sorted numerically in the consoles JSON result.

const test = { "1": "test1", "0": "test2", "2": "test3" };

console.log(test); // {"0": "test2", "1": "test1", "2": "test3"}
.as-console-wrapper { top: 0; max-height: 100% !important; }

If you want to preserve the order of the keys, you will need to store the key order and reference it when sorting the entries inside a custom JSON stringification function. If you only want to sort by the value, this is much simpler, because there is no need for a key order array.

const test = { "1": "test1", "0": "test2", "2": "test3" };
const keyOrder = [ 1, 0, 2 ];

// Sorted by referenced key order
const customJsonStr = (obj, indent = '  ') =>
  `{\n${Object.entries(obj)
    .sort(([ka], [kb]) => keyOrder[ka] - keyOrder[kb])
    .map(([k, v]) => `${indent}"${k}": "${v}"`).join(',\n')}\n}`

// Sorted by value only
const customJsonStr2 = (obj, indent = '  ') =>
  `{\n${Object.entries(obj)
    .sort(([ka, va], [kb, vb]) => va.localeCompare(vb))
    .map(([k, v]) => `${indent}"${k}": "${v}"`).join(',\n')}\n}`

console.log(customJsonStr(test));  // {"1": "test1", "0": "test2", "2": "test3"}
console.log(customJsonStr2(test)); // {"1": "test1", "0": "test2", "2": "test3"}
.as-console-wrapper { top: 0; max-height: 100% !important; }

A: console.log is automatically ordering the output, your JavaScript array itself won't be ordered, unless you call the higher-order function Array.prototype.sort


text:
Q: Remove Time From SSRS Date Parameter
I want to remove the time from my Parameter Selection Dropdown, NOT a cell referencing the parameter

I have a simple parameter weekEndingDate which is fed by my dataset
SELECT TOP (8) Convert(Date,FullDate, 101) AS FullDate
FROM DimDate
WHERE (DayNameOfWeek = 'Friday') AND (CAST(FullDate AS Date) < CAST(GETDATE() AS Date))
ORDER BY FullDate DESC

I have also tried
SELECT TOP (8) CAST(FullDate as Date) AS FullDate
FROM DimDate
WHERE (DayNameOfWeek = 'Friday') AND (CAST(FullDate AS Date) < CAST(GETDATE() AS Date))
ORDER BY FullDate DESC

The issue is that the parameter options still display time.

If I execute the query in Query Designer I get basically correct output (Convert is giving me m/dd/yyyy, instead of mm/dd/yyyy) and this is true for cast and convert, but the parameter drop down still has time, and if I put the parameter into a cell, it also has the time

I have deleted the .data files
I have deleted and recreated the parameter, but did not deploy or rebuild or anything WITHOUT the parameter, I deleted and immediately recreated then hit Preview
I have tried both CAST and CONVERT
I have tried Previewing, Running, and Deploying the report

In all cases the time remains and I am dumbfounded, all help appreciated, and I'm happy to clarify anything

A: Try setting your Parameter Data Type to Text instead of Date/Time.
Also changing the dataset to return varchar was necessary
Final dataset code:
SELECT TOP (8) CAST(CONVERT(Date, FullDate, 101)as VARCHAR) AS FullDate
FROM DimDate
WHERE (DayNameOfWeek = 'Friday') AND (CAST(FullDate AS Date) < CAST(GETDATE() AS Date))
ORDER BY FullDate DESC

A: Sourced from: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/95d23f74-d7d3-41e1-8538-dbeff6e65ee2/ssrs-2008-r2-parameter-datetime-how-to-hide-time

*

*Open your report in SQL Server Business Intelligence Development Studio or Report Builder3.0.

*Click the Design tab, right-click the textbox where you will display the @Time parameter, select expression.

*Clear the expression dialog box, then type in:
=FormatDateTime(Parameters!Timer.Value, DateFormat.ShortDate) or =FormatDateTime(Parameters!Timer.Value,2).


text:
Q: Plural pronoun for singular collective noun how to choose the correct verbs in this sentence?

The person does it because they don't want to leave.
The person does it because they doesn't want to leave.
The person do it because they don't want to leave.


text:
Q: Is there a way to embed a ggplot image dynamically by row (like a sparkline) using the gt package? I'm trying to replicate this process and get the gt package to render ggplot objects where each row in the table gets a different graph (like a spark line).
There appears to be a solution on the linked page, but when I try to replicate it, I get the following error
Error in body[[col]][loc$rows] <- fn(body[[col]][loc$rows]) : replacement has length zero

Could someone please help me debug this? I'm banging my head against the wall here.
Example code:
library(tidyverse)
#> Warning: package 'tibble' was built under R version 3.5.2
library(gt)
library(purrr)

# make a function for creating a plot
# of a group
plot_group <- function(name, df) {
  plot_object <-
    ggplot(data = df,
           aes(x = hp, y = trq,
               size = msrp)) +
    geom_point(color = "blue") +
    theme(legend.position = "none")
  return(plot_object)
}

# make a plot of each mfr
gtcars %>%
  group_by(mfr) %>%
  nest() %>%
  mutate(plot = map2(mfr, data, plot_group)) %>%
  select(-data) %>%
  # Create empty column (a placeholder for the images)
  mutate(ggplot = NA) ->
  tibble_plot

# Minor changes to this code
tibble_plot %>%
  gt() %>%
  text_transform(
    locations = cells_body(vars(ggplot)), # use empty cell as location
    fn = function(x) {
      # Insert each image into each empty cell in `ggplot`
      map(.$plot, ggplot_image, height = px(200))
    }
  )

A: I think I may have found a solution by changing some of the code.
library(ggplot2)
library(gt)
library(tidyr)

# make a plot of each mfr
tibble_plot <- gtcars %>%
group_by(mfr) %>%
nest() %>%
mutate(plot = map(data, ~ggplot(., aes(hp, trq, size = msrp)) + #you could use the function and it should work
                  geom_point() +
                  geom_point(color = "blue") +
                  theme(legend.position = "none"))) %>%
select(-data) %>%
# Create empty column (a placeholder for the images)
mutate(ggplot = NA)

#Creates the length of the tibble
text_names <- gtcars %>%
select(mfr) %>%
unique() %>%
pull()

# Is a bit slow for me
tibble_output <- tibble(
 text = text_names,
 ggplot = NA,
 .rows = length(text_names)) %>%
gt() %>%
text_transform(
 locations = cells_body(vars(ggplot)),
 fn = function(x) {
   map(tibble_plot$plot, ggplot_image, height = px(200))
 }
)

tibble_output

A: This seems to attain what you need and is more concise than the accepted answer.
library(tidyverse)
library(gt)

gtcars %>%
  nest_by(mfr) %>%
  rowwise() %>%
  mutate(
    gg = (
      ggplot(data = data,
             aes(x = hp, y = trq,
                 size = msrp)) +
        geom_point(color = "blue") +
        theme(legend.position = "none")
    ) %>%
      ggplot_image(height = px(200)),
    data = NULL
  ) %>%
  gt() %>%
  fmt_markdown(vars(gg))


text:
Q: play multiple flv file in single swf object I have one swf object in my site.
I have to read data from database and after fetching data of video names,
I need to play those video in single swf object one by one, means after completion of first video second video will start.
Thanks in advance.

A: Assuming you are using NetStream, you have to listen to NetStream onPlayStatus event and then load another flv with the play(...) method

A: Lee Brimelow has a tutorial here for building your own video player in AS3, this should help to get you started - though from the way you're talking about it I get the sense that you're not really a flash developer, you just have to work with flash for this project - so what you're asking for may be a little more complex than you expect.
First watch this:
http://gotoandlearn.com/play?id=46
Then understand that when you build a player it fires certain "events" at certain times. Like kajyr above says, you need to listen for a specific event that tells you that the current clip is over. When that even fires, you have to tell your player to play the next clip.
What you're asking for is entirely possible and even easy if you understand the basics behind it. I built a tool that handles dynamic playlisting etc at my old job and it only took about a day to give it every feature we needed. But you do need to understand how AS3 works in order to make this work.
Alternately you may be able to find some sort of video sequencing app at http://activeden.net/ - they have a lot of pre-built flash components and that's another way to go.

A: Simply we can create a playlist for that...
Some googeling helps me for this.
check out this


text:
Q: supertabular: how to change font size and add caption? 1) How to use small or tiny fonts in supertabular ?
2) How to embed captions in supertabular?
I tried some possible options but they are not working.
\documentclass{article}
\usepackage{supertabular}
\begin{document}
\begin{supertabular}{ll}
    \hline
    AA & BB\\
    CC & DD\\
    \hline
\end{supertabular}
\end{document}

A: supertabular provides a caption mechanism that is quite different from the standard captions. The following three commands are provided: \tablecaption, \topcaption and \bottomcaption that position the caption accordingly.
To position the caption only on the last page under the table, use \bottomcaption as shown in the following MWE:
\documentclass{article}
\usepackage{supertabular}
\begin{document}
\bottomcaption{some caption}
\begin{supertabular}{ll}
    \hline
    AA & BB\\
    CC & DD\\
    \hline
\end{supertabular}
\end{document}

Changing the font size in a supertabular could be done as follows. In this case, \small affects all the whole table, while \tiny only affects the following cell.
\documentclass{article}
\usepackage{supertabular}
\begin{document}
\bottomcaption{some caption}\small
\begin{supertabular}{ll}
    \hline
    AA & BB\\
    \tiny CC & DD\\
    \hline
\end{supertabular}
\end{document}


text:
Q: How can I evaluate all the combinations obtained by GridSearchCV? By using GridSearchCV I can obtain clf.cv_results_['params'] and I would like to run over all the possible combinations and printing some probabilities:
for params in zip(clf.cv_results_['params']):
        print(params)
        clf= SVC(params)
        clf.fit(X_train, y_train)
        z_test=clf.predict(X_test)
        print("Probability 1:", prob_error(y_test,z_test))
        print("Probability 2:", average_error(y_test,z_test))

However, in params I obtain this:
({'C': 1000, 'gamma': 1000, 'tol': 2},)

How can I transform this in order to do the fit of the algorithm? Because this code has an error in "clf.fit(X_train, y_train)":
TypeError: must be real number, not tuple

A: Why are you using zip on the clf.cv_results_['params']. Remove that and do it like below:
for params in clf.cv_results_['params']:
        print(params)
        clf= SVC(**params)
        clf.fit(X_train, y_train)
        z_test=clf.predict(X_test)
        print("Probability 1:", prob_error(y_test,z_test))
        print("Probability 2:", average_error(y_test,z_test))

See this for more details:

*

*How to pass dictionary items as function arguments in python?


text:
Q: How do I tell if the value of a variable is a symbol bound to a procedure in Scheme? I am familiar with Common Lisp and trying to learn some Scheme, so I have been trying to understand how I'd use Scheme for things I usually code in Common Lisp.
In Common Lisp there's fboundp, which tells me if a symbol (the value of a variable) is bound to a function. So, I would do this:
(let ((s (read)))
  (if (fboundp s)
      (apply (symbol-function s) args)
      (error ...)))

Is that possible in Scheme? I've been trying to find this in the R6RS spec but coudn't find anything similar.

A: This way?

*

*check if it is a symbol

*evaluate the symbol using EVAL to get its value

*check if the result is a procedure with PROCEDURE?

A: In Scheme, functions are not tied to symbols like they are in Common Lisp. If you need to know, whether a value is actually a procedure, you can use the procedure? predicate:
(if (procedure? s) (do-something-with s) (do-something-else))

There is no direct way in portable Scheme to achieve, what your example code wants to do, as symbols in Scheme are simply kind of unified strings, lacking Common Lisp's value/function/plist slots.
You could try something like:
(define function-table (list `(car ,car) `(cdr ,cdr) `(cons ,cons) `(display ,display)))

(let* ((s (read))
       (f (cond ((assq s function-table) => cadr)
                (else (error "undefined function")))))
    (apply f args))

i.e., defining your own mapping of "good" functions. This would have the advantage, that you can limit the set of function to only "safe" ones, or whatsoever.


text:
Q: How do I include an array as part of a struct definition in GO? I am trying to parse a relatively complex bit of JSON. It has direct nodes, and it has arrays that have a variable number of elements.  Here is a sample:
{
status: 200,
generated: "2014-07-23T13:09:30.315Z",
copyright: "Copyright (c) 2014 Us Not You. All Rights Reserved.",
results: 1,
start: 0,
links: {
        next: null,
        prev: null,
        self: "http://thing.com/thing.json"
    },
docs: [
        {
            id: "thingID_001",
        }
    ]
}

Simplified, of course.  There may be zero or more docs each of which has a number of nodes.  "links" is easy, I define a struct with the correct fields and there we go.  But docs, I cannot get to marshal.  Here is my code:
import (
    "net/http"
    "fmt"
    "io/ioutil"
    "encoding/json"
)
type Thinglinks struct {
    Next string
    Prev string
    Self string
}
//type ThingDoc struct {
//    Id string
//   Type string
//}
type ThingSection struct {
    Status int
    Generated string
    Copyright string
    Results int
    Start int
    Links thinglinks
    Docs []map[string]interface{}
}

func main() {
    resp, err := http.Get("http://thing.com/thing.json")
    if err != nil {
        fmt.Println(err)
        }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    var s ThingSection
    err3 := json.Unmarshal(body, &s)
    if err3 == nil {
        fmt.Println(s)
        fmt.Println(s.Links.Self)
        if len(s.Docs) >0 {
            fmt.Println(s.Docs[0])
        }
    } else {
        fmt.Println(err3)
    }
}

When I compile and run I get my expected results for all the nodes except Docs, which is always an empty set.
I strongly suspect that it is the "Docs" definition in the type declaration for the ThingSection struct, but I haven't been able to figure out what to do there.
Any assistance?

A: If that is your actual JSON you will have issues. JSON needs quotes around field names as seen in the language definition here: http://json.org/ and you may not have extraneous commas.
I have this bit on the playground and it works for me just fine after adding the quotes and removing the extraneous ',' inside the docs.
http://play.golang.org/p/6OYeTuftfg


text:
Q: Uncaught HierarchyRequestError I'm a beginner with dart and polymer. When I run the web app in Chrome I get:
Uncaught HierarchyRequestError: Failed to execute 'appendChild' on 'Node': Nodes of type 'HTML' may not be inserted inside nodes of type '#document'. patches-mdv.js:57
(anonymous function) patches-mdv.js:57
(anonymous function) patches-mdv.js:57
(anonymous function) patches-mdv.js:57

The appendChild is probably in generated dart2js code, namely in the following piece:
  Node: {
    "^": "EventTarget;ownerDocument=,text:textContent=",
    remove$0: function(receiver) {
      var t1 = receiver.parentNode;
      if (t1 != null)
        J._removeChild$1$x(t1, receiver);
    },
    toString$0: function(receiver) {
      var t1 = receiver.nodeValue;
      return t1 == null ? J.Interceptor.prototype.toString$0.call(this, receiver) : t1;
    },
    append$1: function(receiver, newChild) {
      return receiver.appendChild(newChild);
    },
    insertBefore$2: function(receiver, newChild, refChild) {
      return receiver.insertBefore(newChild, refChild);
    },
    _removeChild$1: function(receiver, oldChild) {
      return receiver.removeChild(oldChild);
    },
    _replaceChild$2: function(receiver, newChild, oldChild) {
      return receiver.replaceChild(newChild, oldChild);
    },
    $isNode: true,
    "%": "DocumentType|Notation;Node"
  },

How do I solve this?

A: As said on https://groups.google.com/a/dartlang.org/forum/#!msg/web/bgMajiu_iR4/rygd5Ftk668J, from the symptoms, it looks like platform.js has been loaded twice.
So remove the following two lines from every html except your toplevel index.html:
<script src="packages/web_components/platform.js"></script>
<script src="packages/web_components/dart_support.js"></script>

Update:
With Polymer > 0.14.0 platform.js is not necessary anymore. It is added automatically by pub build and pub serve.


text:
Q: получить нужную локаль для системы Например у меня в линуксе стоит есть локаль ru_RU.UTF-8. Для игры, чтобы правильно работал русский шрифт при вводе текста, мне нужно писать такую команду.
setlocale ( LC_ALL, "ru_RU.UTF-8" );

Но дело в том, что если мою программу или игру вдруг запустят в бразилии например, то у они не смогут ввести текст своего алфавита, если у них не английский. Вот и вопрос. Как мне узнать какая локаль для системы на первом месте? Неужели мне надо будет по файлам бегать и смотреть какие есть локали. И как это сделать в линукс и windows?

A: Задать системную локаль, взятую из переменной окружения:
setlocale(LC_ALL, "");

Получить имя текущей локали приложения, не изменяя её:
std::string current_locale = setlocale(LC_ALL, nullptr);


text:
Q: How to save the template with dynamic data in django I want to save the template with the dynamic data when ever i request it should render the saved page instead of querying again the database. my app is in views.py below is my sample code. please help.
def severity_wise(request):
    sev_chart=[["Severity","No. of Bugs"]]
    sev_list=["1","2","3","4","5","6"]

   for i in sev_list:
             sev=dev_report.objects.filter(Q(severity=i),Q(status='S')|Q(status='N')|Q(status='A')|Q(status='O')|Q(status='W')|Q(status='I')|Q(status='P')|Q(status='H'))
    list=["S"+i,len(sev)]
    sev_chart.append(list)
    sev_table=sev_chart[1:]
return render(request, 'WASS/severity_wise.html',{'sc':sev_chart , 'sl':sev_table })

A: You can use cache_page decorator for the same.
@cache_page(60 * 15)
def severity_wise(request):
    sev_chart=[["Severity","No. of Bugs"]]
    ......

For further reading click here

A: hi I found an another method that to rendering to file.
from django.template.loader import render_to_string
open(filename, "w").write(render_to_string(template, context))

and i am calling the filename(rendered page) in another app.


text:
Q: @RestController @RequestMapping not working in spring boot gradle project (404 error) I have two controllers called ControllerA and ControllerB in Kotlin&Spring project
They both have @RestController, @RequestMapping but ControllerB gets 404 error while the other works well.
// ControllerA
@RestController
@RequestMapping("/user")
class ControllerA {

    var userService: UserService = UserService();

    @GetMapping("/")
    fun userList(): Any {

        val userList: List<String> = userService.findUserList()

        if (userList.isEmpty()){
            return "no user"
        }
        return userList
    }

...

// ControllerB
@RestController
@RequestMapping("/user2")
class ControllerB (

    private val homeworkService: HomeworkService // 생성자 주입

){

    @GetMapping("/")
    fun getAllUsers() = homeworkService.getAllUser()

...

http://localhost:8080/user/ seems to call ControllerA but http://localhost:8080/user2/ doesn't work.
My package path looks like this
\package
\package\package
\package\package\packageApplication.kt
\package\package\controller
\package\package\controllerA.kt
\package\package\controllerB.kt
I think my class path is right. What's wrong with my controllers ;(


text:
Q: delete one table with join on multiple table with where condition I am trying to delete a row from skills_jobs table
following is my query
delete from skills_jobs skj inner join jobs j on skj.jobid=j.id inner join users u on u.id=j.userid where u.id=$userid

but it throws the following error;

Fatal error: Uncaught exception 'Exception' with message 'You have an
  error in your SQL syntax; check the manual that corresponds to your
  MySQL server version for the right syntax to use near 'skj inner join
  jobs j on skj.jobid=j.id inner join users u on u.id=j.userid wher' at
  line 1 query: delete from skills_jobs skj inner join jobs j on
  skj.jobid=j.id inner join users u on u.id=j.userid where u.id=41

A: You must set table, from which you remove row, then try:
DELETE skills_jobs from skills_jobs INNER JOIN jobs j ON skills_jobs.jobid=j.id INNER JOIN users u ON u.id=j.userid WHERE u.id=$userid

See section "Multi-Table Deletes" from https://dev.mysql.com/doc/refman/5.7/en/delete.html

A: It should be like this
skills_jobs skj inner join jobs j on skj.jobid=j.id

You forgot on in the syntax
So the correct syntax will look like this:-
delete from skills_jobs skj inner join jobs j on skj.jobid=j.id inner join users u on u.id=j.userid where u.id=$userid

Hope this helps!

A: delete from skills_jobs skj
inner join jobs j ON skj.jobid=j.id
inner join users u ON u.id=j.userid
where u.id=$userid

Try above code.
Hope this will helps.

A: DELETE FROM skills_jobs skj INNER JOIN jobs j ON j.id=skj.jobid INNER JOIN
users u ON u.id=j.userid
WHERE u.id=$userid

A:  DELETE FROM skj USING `skills_jobs` AS skj
 INNER JOIN `jobs` AS j ON skj.`jobid` = j.`id`
 INNER JOIN `users` AS u ON u.`id` = j.`userid`
 WHERE u.`id` = $userid

If you declare an alias for a table, you must use the alias when referring to the table.
Another structured answer:
DELETE skj FROM `skills_jobs` AS skj
INNER JOIN `jobs` AS j ON skj.`jobid`=j.`id`
INNER JOIN `users` AS u ON u.`id`=j.`userid`
WHERE u.`id`=$userid


text:
Q: Clear Memcached on CakePHP 3.4 I'm using memcached engine on CakePHP 3.4.
I would like to use a simple command in PHP, empty all content stored in memcached.
I followed the documentation, it works very well by emptying an item.
Exemple : Cache::delete('products', 'mymemconfig'); works fine.
Now, how can i do tu remove all cache keys stored in mymemconfig ?
I tried Cache::clear(false, 'mymemconfig');, that does'n work...
Would you have a solution?


text:
Q: Improving speed of ParametricNDSolve for three-dimensional integration I'm trying to calculate a three-dimensional integral of a function depending on four parameters a, b, c, d via ParametricNDSolve after NIntegrate didn't really work out. My solution so far looks like this:
sol1 = ParametricNDSolve[ {Boole[
      Sqrt[(x - xj[a, c][[1]])^2 + y^2 + z^2] >= 1 \[And]
       Sqrt[(x - xj[a, c][[2]])^2 + y^2 + z^2] >= a]*
     integrand[a, b, c, d, x, y, z] == f'[x],
   f[-100] == 0}, f, {x, -100, 150}, {y, z, a, b, c, d}]
func1 = Evaluate[f /. sol1]
intx[y_, z_, a_, b_, c_, d_] := func1[y, z, a, b, c, d][150]

sol2 = ParametricNDSolve[{intx[y, z, a, b, c, d] == f'[y],
   f[-10] == 0}, f, {y, -10, 10}, {z, a, b, c, d}]
func2 = Evaluate[f /. sol2]
intxy[z_, a_, b_, c_, d_] := func2[z, a, b, c, d][10]

sol3 = ParametricNDSolve[{intxy[z, a, b, c, d] == f'[z],
   f[-10] == 0}, f, {z, -10, 10},  {a, b, c, d}]
func3 = Evaluate[f /. sol3]
intxyz[a_, b_, c_, d_] := func3[a, b, c, d][10]

This solution however works quite slowly. For reference: Evaluation of intx for a set of parameters happens almost instantly, evaluation of intxy takes 1-2 seconds and evaluation of intxyz takes about 4 minutes. As my goal is to plot intxyz for three fixed and one variable parameter a, b, c, d, this calculation takes far too long. Is there a way to improve the speed of ParametricNDSolve or would another method to calculate the integral be better suited for this problem?
EDIT:
integrand is given by

integrand[a_, b_, c_, d_, x_, y_, z_] :=
 2*Re[Conjugate[
     u0[a, b, c, d, x, y, z]].
     (u0[a, b, c, d, x, y, z][[1]]*
       Derivative[1, 0, 0, 0, 0][ut][x, y, z, a, c] +
      u0[a, b, c, d, x, y, z][[2]]*
       Derivative[0, 1, 0, 0, 0][ut][x, y, z, a, c] +
      u0[a, b, c, d, x, y, z][[3]]*
       Derivative[0, 0, 1, 0, 0][ut][x, y, z, a, c]
       - {Derivative[1, 0, 0, 0, 0][ut][x, y, z, a, c][[3]],
          Derivative[0, 1, 0, 0, 0][ut][x, y, z, a, c][[3]],
          Derivative[0, 0, 1, 0, 0][ut][x, y, z, a, c][[3]]})]

where u0 and ut are vector fields consisting of mainly polynomials and exponential functions of r=Sqrt[x^2+y^2+z^2].


text:
Q: Efficient way to count Columns I need some efficient way to count columns in .txt file. My file format:
123.222  333.333  454.45  453.333
14.222  3.333  434.45  423.333
33.2  223.333  434.45  153.333

So I tried this one:
StreamReader sr = new StreamReader(_path);
int ColumnsCount = Array.ConvertAll(sr.ReadLine().Split('  '), Double.Parse).Count();

First line is enough to get column count in this text format.

A: You are almost as fast as you can go. If you need the conversion, just do this:
int ColumnsCount = Array.ConvertAll(sr.ReadLine().Split(' '), Double.Parse).Length;

Using Length instead of Count saves you an enumeration of the collection. If you don't need to convert, just do:
sr.ReadLine().Split(' ').Length;

Otherwise, you still need to always do the read, and always Split the line. Since there is no way around that, its as fast as you can go.

A: You can avoid double.Parse, since you are only interested in the column count and use Split with remove empty entries option. You can also use File.ReadLine and just read the first line like:
string firstLine = File.ReadLines("filePath").First();
int ColumnsCount = 0;
if (firstLine != null)
{
    ColumnsCount = firstLine.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries).Length;
}

How much faster this would be, I am not sure, even if there is going to be a difference I believe it would be negligible.

A: Here is a quick answer to this. No need to do the string split, simply treat the string as a character array, and count the spaces.  This also assumes that you cannot have a 0 column table.
var columnCount = 1;
foreach(var c in File.ReadLines("filePath").First() ?? String.Empty)
{
   if (c == ' ')
   {
      columnCount++;
   }
}

return columnCount;


text:
Q: Use execve with argv (Piping) I got the piping of several commands working. Now Id like to execute this with received arguments (*argv[]) and not hard coded like here.
Ived tried using the rest of the execve family but no progress.
Ive been thinking to put everything (argv) in an array of pointers and adding NULL at the end of where each pointer points, then iterate through it.
Passed argument ( , included): echo "test" , wc , cowsay
int main(int argc, char *argv[]) {

    char *echo[] = {"echo", "test", NULL};
    char *rev[] = {"rev", NULL};
    char *wc[] = {"wc", NULL};
    char **cmd[] = {echo, wc, rev, NULL};

    loop_pipe(cmd);
    return (0);
}

void loop_pipe(char ***cmd) {
    int p[2];
    pid_t pid;
    int fd_in = 0;

    while (*cmd != NULL) {
        pipe(p);
        if ((pid = fork()) == -1) {
            exit(EXIT_FAILURE);
        } else if (pid == 0) {
            dup2(fd_in, 0); //change the input according to the old one
            if (*(cmd + 1) != NULL)
                dup2(p[1], 1);
            close(p[0]);
            execvp((*cmd)[0], *cmd);
            exit(EXIT_FAILURE);
        } else {
            wait(NULL);
            close(p[1]);
            fd_in = p[0]; //save the input for the next command
            cmd++;
        }
    }
}

A: You did all the multiprocessing part. You only need to do some array shuffling, to convert array of strings to array of arrays of strings.
If you don't mind iterating the array two times, you can do like the following:
int main(int argc, char *argv[]) {
    // count the commas
    int n = 0;
    for (int k = 1; k < argc; k++) {
        if (strcmp(argv[k], ",") == 0)
            n++;
    }
    int stage_count = n + 1;

    // allocate the pipeline stage list
    char ***cmd = calloc(stage_count + 1, sizeof(char**));

    // fill arguments for each stage
    int stage = 0;
    int first_arg = 1; // index of the first argument of current stage
    for (int k = 1; k <= argc; k++) {
        // stage arguments are terminated by a comma,
        // except of the last, where k == argc
        if ((k == argc) || (strcmp(argv[k], ",") == 0)) {
            // now, k is one greater than the index of the last argument of that stage
            int arg_count = k - first_arg;

            // save arguments for one pipeline stage
            // (note that only char pointers are copied, not the data they point to)
            // (also, you can use `malloc` but don't forget to write terminating NULL then)
            char **args = calloc(arg_count + 1, sizeof(char*));
            memcpy(args, argv + first_arg, arg_count * sizeof(char*));
            cmd[stage] = args;

            stage++;
            first_arg = k + 1; // k refers to the delimiter so the next stage arguments start at k+1
        }
    }

    loop_pipe(cmd);
    return 0;
}

You can refine this using special properties of argv, e.g. that argv[argc] == NULL, or that argv, as well as the argument strings themselves, is actually writable.


text:
Q: Report sometimes returns 0 records in SAP GUI script So I've recorded a script using the SAP GUI recorder. I'm basically just running 7 reports and saving the contents to an excel file. The code is uninspiring, just some variation of.

session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "SAP_ALL.TXT"
session.findById("wnd[1]/usr/ctxtDY_FILENAME").caretPosition = 11

But sometimes there are no records in the report.

*

*I suspect there is something I can check to either save the report or move on using if/then/else but cannot find a good example. How do I catch and recover from this or other errors?

*Is there a way to to sapshcut�or structure the script to avoid this problem?

*Also, is there a way to execute the script from the command line, passing in the userid and password as parameters?

Relevant examples welcome. I'd RTFM but I don't have one.

A: *

*If the report is a grid, then you could try the following.

for example:
...
session.findById("wnd[0]/tbar[1]/btn[8]").press
on error resume next
'This command must be recorded once in your environment. It's a   mouseclick in the first line.
session.findById("wnd[0]/usr  /subSUB_AREA_ROOT:SAPLREIS_GUI_CONTROLLER:0200/subSUB_AREA:SAPLREIS_GUI_CONTROLLER:1000/cntlCC_LIST/shellcont/shell").currentCellRow = 1
if err.number = 0 then
   on error goto 0
   ...
   session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "SAP_ALL.TXT"
   session.findById("wnd[1]/usr/ctxtDY_FILENAME").caretPosition = 11
   ...
else
   on error goto 0
   ...
end if
...

*Please take a look at the following link:

VBA 2010 - Hide all SAP windows using .iconify
Regards,
ScriptMan


text:
Q: Pentaho reports with OLAP data source and SAP - poor performance I have few BEx queries (OLAP cubes for third-party client) and .prpt reports in Pentaho that uses these BEx via OLAP data source (OLAP4J, MDX). When I execute these BEx in SAP BW or even directly as SOAP service (XML/A execute command via SoapUI) I'm getting result very fast, just 2-3 seconds. But when I try to execute the same BEx queries in Pentaho I'm getting results after 1-2 minutes It doesn't matter if I execute reports that are already published on Pentaho BI server or if I execute these reports in Report Designer. Caching is enabled.
MDX-query is simple select.
As captured with Wireshark, Pentaho does multiple http requests to get metadata about all existing cubes (and their measures too!) in current catalogue.
Capture of network packets in attachments. There are more than 400 http requests that perform by Pentaho to execute just one MDX select statement.
It is OK that Pentaho tries to get metadata information by specified cube, but executing MDX query twice and getting metadata of all other cubes from catalogue is very unefficiently.
Previously I read about similar problem with SSAS. But this information doesn't help with SAP XML/A provider. Changes in OLAP4J driver (in org.olap4j.driver.xmla.XmlaOlap4jCellSet and org.olap4j.driver.xmla.XmlaOlap4jCube) cause unstable rendering of reports.
So the main question is: how to improve performance?
XML/A requests capture


text:
Q: Unable to mount Drive1 - Not Authorized I'm using Ubuntu server 12.04 on my HP Proliant microserver.
I am using webmin/vnc/ssh to administer it.
I'm trying to mount a drive which I had previously used on the same kit but with OpenMediaVault. In OMV I had formatted the disk as xfs.
When I try to access the disk in Ubuntu I get:
Unable to mount Drive1 - Not Authorized

I've tried mounting the disk in Webmin but it has no option for xfs.
I'm quite new to Linux so can anyone assist me?

A: It looks like you are trying to mount the entire disk (/dev/sdb) rather than a partition on the disk (such as /dev/sdb1).  Do you know which partition on the disk you need to mount?  It's probably sdb1, but not necessarily.


text:
Q: Django how to shuffle a queryset without speed lose I want to shuffle a list of objects without losing any speed in terms of optimization and performance speed.
let's say I have the following query.
related_products = Announcement.objects.filter(category=category).exclude(id=announcement.id)

pythonically, i would import the random module and then random.shuffle(related_products). But I am not sure if it will store something in the memory on my view or use some CPU speed or whatever terminology I don't know.
So I wonder what's the best way to make it optimized.
Thanks!

A: If the list of related_products objects is reasonably short and if you are going to be using them all in any case, It's simplest to just fetch them and then shuffle them.
import random
...

products = random.shuffle( list( related_products) )
for product in products:
    ...

This is efficient, in that no objects are copied. The main issue is if it's possible that the quantity is excessive. You can use related_products.count() to find out how many there are, before fetching any from the DB.
There's also queryset .order_by('?') which retrieves in random order, but the documentation says "Note: order_by('?') queries may be expensive and slow, depending on the database backend you're using."
A third possibility for sampling would be to fetch just the primary keys of every row in the table. Shuffle and slice those to get a sample of the required size, then fetch just those objects.
product_pks = related_products.values_list('pk', flat=True)
sampled_pks = random.shuffle( list(product_pks))[:N_SAMPLE]
products = related_products.filter( pk__in = sampled_pks )

No idea how this would perform, but it's two DB queries and the first fetches the minimum amount of data necessary  for shuffling.


text:
Q: Inline char to std::string conversion Is there a built-in method for constructing a std::string based on a given char?
The reason I ask this is because I want to make a function call directly within the if statement:
// Given function prototype
bool func(std::string s);

for(auto rit = s.rbegin(); rit != s.rend(); ++rit)
{
    if(func(*rit))
    {
        //
    }
}

I've tried the following:
std::string(*rit)
static_cast<std::string>(*rit)

A: The most concise way since C++11 is to construct via an initializer list:
func({*rit})

or if you need to explicitly specify the type (for a function template):
func(std::string{*rit})

For pre-C++11, it is the 2nd overload of the std::string's constructor:
func(std::string(1, *rit))


text:
Q: Why is my Map broken? Scenario: Creating a server which has Room objects which contain User objects.
I want to store the rooms in a Map of some sort by Id (a string).
Desired Behavior:
When a user makes a request via the server, I should be able to look up the Room by id from the library and then add the user to the room, if that's what the request needs.
Currently I use the static function in my Library.java class where the Map is stored to retrieve Rooms:
public class Library {

  private static Hashtable<String, Rooms> myRooms = new Hashtable<String, Rooms>();

  public static addRoom(String s, Room r) {
    myRooms.put(s, r);
  }

  public static Room getRoomById(String s) {
    return myRooms.get(s);
  }
}

In another class I'll do the equivalent of myRoom.addUser(user);
What I'm observing using Hashtable, is that no matter how many times I add a user to the Room returned by getRoomById, the user is not in the room later.
I thought that in Java, the object that was returned was essentially a reference to the  data, the same object that was in the Hashtable with the same references; but, it isn't behaving like that. Is there a way to get this behavior? Maybe with a wrapper of some sort? Am I just using the wrong variant of map?
Help?

A: It's very peculiar that you declare myRooms as Hashtable<String, Rooms> (plural Rooms), but you put a singular Room r in addRoom.
Are you trying to do some sort of multimap, where a key can map to a multiple values? If so, then either us the Guava implementation, or implement your own as a Map<K,Set<V>> (map a key to a set of values).
I'm not sure if this your fundamental issue, though.
It is correct that the returned value by get should be the same object, as defined by reference equality, as the one used in put.
    Object someObject = new Object();
    Map<String,Object> map = new HashMap<String,Object>();
    map.put("key1", someObject);
    System.out.println(map.get("key1") == someObject); // prints "true"

    someObject = "something else";
    System.out.println(map.get("key1") == someObject); // prints "false"

The above is expected behavior.
Sometimes people have trouble with a Map because their key objects do not implement hashCode and equals contract properly, but if you're using String as keys, this should not be an issue.
By the way, Hashtable has a newer, sexier cousin in HashMap. I noticed the multithreading tag in the question, so if you actually need the synchronized feature, you can use Collections.synchronizedMap
In either case, whether you use a HashMap or a Hashtable, you want declare  myRooms simply as a Map (see Effective Java 2nd Edition, Item 52: Refer to objects by their interfaces).
Related questions

*

*Overriding equals and hashCode in Java

*Understanding the workings of equals and hashCode in a HashMap

*Java hashmap vs hashtable

*Difference between a Deprecated and Legacy API?

A: Does your code even compile?
public class Library {

  private static Hashtable<String, Rooms> myRooms = new Hashtable<String, Rooms>();

  public static addRoom(String s, Room r) { // Your hashtable holds Rooms yet you add a Room
    myRooms.put(s, r);
  }

  public static Room getRoomById(String s) { // Again, returning a Room, instead of Rooms
    return myRooms.get(s);
  }
}

Just by looking at this, it shouldn't compile. Now I can only assume that it was a typo, and if that's the case then show us the Room code where you're trying to add a user to the room.


text:
Q: Excel - Copy each value as many times as there are sequence numbers in another column I have the below dataset:
A B
1 Apple
2 Mango
3 Orange

And I'm trying to replicate each value of the B column as many times as there are sequence numbers in the A column (same sheet or another sheet doesn't matter):
A B
1 Apple
2 Apple
3 Apple
1 Mango
2 Mango
3 Mango
1 Orange
2 Orange
3 Orange

But I'm unable to come up with a way to achieve this. How do I achieve this without VBA?


text:
Q: Где найти видео курс по jsp Желательно, в котором создают сайт с логином, маленьким блогом и какими-нибудь апплетами.
A: Вбей в google: Developing Enterprise Application using EJB. Web programing with Servlets and JSP.


text:
Q: An intuitive explanation of the primal-dual algorithm I am a beginner to optimization, and I am trying to understand the primal-dual algorithm. However, all explanations I have seen so far are very maths-heavy. So it's very difficult to understand the details without having a broader appreciation of what is generally going on.
Can somebody give me an intuitive / wordy / analagous explanation of how the algorithm works, and what it is used for?
Thanks!


text:
Q: Get 1 row only from MySQL in CodeIgniter i want to take only 1 row from database with no loop when i call it.
this is my code on CodeIgniter
$row = $this->db->get_where('tr_supervision',array('EMP_ID_MEMBER' => $EMP_ID));

    echo $row['EMP_ID_LEADER'];

i dunno how but i get the error
An uncaught Exception was encountered
Type: Error
Message: Cannot use object of type CI_DB_mysqli_result as array
Filename: C:\laragon\www\onlineform\application\controllers\Reimbursement.php
Line Number: 96
Backtrace:
File: C:\laragon\www\onlineform\index.php
Line: 315
Function: require_once

A: In that case your use it like this:
$row = $this->db->where('EMP_ID_MEMBER',$EMP_ID)
         ->get('tr_supervision')
         ->row_array();

echo $row['EMP_ID_LEADER'];

Please read more about query results here:
https://codeigniter.com/userguide3/database/results.html?highlight=query%20results

A: $this->db->where('EMP_ID_MEMBER',$EMP_ID)
         ->get('tr_supervision')
         ->row_array();


text:
Q: Python package/module import functions from sub packages I'm building a python package to do some auditing of systems at work.  Thus far I've been able to work with using free floating .py files and and running the main file in the same directory as the module files.  At a high level I want to create a package that holds several subpackages for specific audits.  bigpackage>subpackage>modulefile.py I want to be able to import specific functions/methods from the modulefile.  How can I accomplish this?
I have the __init__ files in place for all my packages and can access them with the usual from bigpackage import modulefile and run them using the dot operator like modulefile.function1(bla, bla, bla) I would like to be able to import specific functions directly so I can run without using the dot operator like function1(bla, bla, bla).

A: from bigpackage.subpackage.modulefile import function1, function2

function1(bla, bla, bla)

A: From:
How to import a module given the full path?
my directory layout:
/my_package
    /__init__.py
    /testfile.py
    /my_module
        /__init__.py

method 1:
import imp
my_module = imp.load_sourc('my_module','.my_module/__init__.py')
my_module.function1()

or for restricted importing:
import sys
import os
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from my_module import function1
function1()


text:
Q: I added a reference to the main project, but the testing project still doesn't see the classes of main My solution has a project that contains all the program logic.
I created a unit test project, added a reference to the main project, but still can't use classes from it to create tests.
My code:
namespace Program
{
    public class Class
    {
        public Class()
        {
        ///
        }

        public int foo()
        {
        ///
        }
    }
}

My tests code:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Program; // cs0246

namespace ProgramTests
{
    [TestClass]
    public class ClassTests
    {
        [TestMethod]
        public void foo_()
        {
            // Arrange
            Class testClass; // this code also have cs0246 error
            // Act

            // Assert
        }
    }
}

In this code, using Program; underlined in red with cs0246 error. But namespace ProgramTests have the reference to Program (there is a checkmark in the reference manager). How can i fix it?
Image of Solution Explorer

A: Please, check the framework version you are using. Maybe Tests library has framework which is no compatible with ClassLib Framework


text:
Q: Frobenius Endomorphism on $F_p$ I'm studying a bit of field theory, and had a quick question about the Frobenius endomorphism, $\phi : K \rightarrow K$. For any prime $p$, is the Frobenius endomorphism on $F_p$ (the finite field with $p$ elements) the identity automorphism?
My reasoning is from working in $\mathbb{Z}/p\mathbb{Z}$, as $F_p \cong \mathbb{Z}/p\mathbb{Z}$. By Fermat's Little Theorem, $\forall x\in \mathbb{Z}$, $x^p\equiv x \mod p$, so
$
\phi(x) = x^p \mod p = x \mod p
$
and therefore $\phi$ fixes all elements of $\mathbb{Z}/p\mathbb{Z}$ and is the identity on $F_p$.
Is this correct? I'm asking because I haven't been able to find anything to support this claim anywhere-- I'm not sure if I've simply created a false statement and made an error in my justification for it. Thanks!


text:
Q: Status of 422 - CloudFront to ELB connection I have created two EC2 instances and put them on Loadbalancer.
By using the Application LoadBalancer URL I am able to login that EC2 instance and doing all.
But While I configure Cloudfront to ELB

*

*Using Cloudfront SSL

*Cloud front To ELB connection on port 80

and hit CloudFront URL on the browser I am able to get the login page of my application.
While a sign in to my application it will give me an error like:
sign_in:1 Failed to load resource: the server responded with a status of 422 ()

My Cloudfront settings is as below:

*I am using the Nginx server.
In Nginx, I have also configured:
add_header 'Access-Control-Allow-Origin' '*' always;

Question:  Is there any missing setting in CloudFront or Nginx server?


text:
Q: Equivalent in C# to Haskell's Data.List.Span Hello is there any efficient method implemented already to get the functionality of Haskell Data.List.span?
span :: (a -> Bool) -> [a] -> ([a], [a])

Basically given a list and a predicate i want to split the list in two after the first occurence of a false predicate.The elements after the pivot element that tests False may or may not respect the predicate , but I do not care.
List: [1,2,3,1,2,3]
Predicate: x<3
Span:  `span  (x<3) [1,2,3,1,2,3]`   =>  `([1,2],[3,1,2,3])`

Update
I do not care of the elements after the first false predicate.I just want to split the list at the first occurence of False predicate. The sequence can be True after the first False predicate but I still want to split it.

A: You could make use of TakeWhile and Skip:
public static IEnumerable<IEnumerable<T>> SplitWhen<T>(this IEnumerable<T> enumerable, Func<T, bool> predicate)
{
    var first = enumerable.TakeWhile(predicate);
    yield return first;
    var second = enumerable.Skip(first.Count());
    yield return second;
}

Update
To avoid multiple iterations, and not requiring the use of a list or array:
public static IEnumerable<IEnumerable<T>> SplitWhen<T>(this IEnumerable<T> enumerable, Func<T, bool> predicate)
{
    yield return enumerable.TakeWhile(predicate);
    yield return enumerable.TakeAfter(predicate);
}

public static IEnumerable<T> TakeAfter<T>(this IEnumerable<T> enumerable, Func<T, bool> predicate)
{
    bool yielding = false;
    foreach (T item in enumerable)
    {
        if (yielding = yielding || !predicate(item))
        {
            yield return item;
        }
    }
}

A: If you are happy with using lists, then you can make a single pass through the source list to create two new lists, like so:
public static (List<T> part1, List<T> part2) SplitListBy<T>(List<T> source, Predicate<T> splitWhen)
{
    var part1 = new List<T>();

    int i;

    for (i = 0; i < source.Count && !splitWhen(source[i]); ++i)
        part1.Add(source[i]);

    var part2 = source.GetRange(i, source.Count - i);

    return (part1, part2);
}

This should be extremely performant. Note that this uses a tuple to return the two lists, which requires C# 7 or later. If you can't use c# 7+, you'll have to change the code to use an out parameter to return one of the lists.
Test code:
var list = new List<int>{ 1, 2, 3, 1, 2, 3 };

var (part1, part2) = SplitListBy(list, item => item >= 3);

Console.WriteLine(string.Join(", ", part1));
Console.WriteLine(string.Join(", ", part2));

Output:
1, 2
3, 1, 2, 3

If you don't need two new lists, but just want to use the original list for one part and a single new list for the other part, you can do it like this:
public static List<T> SplitListBy<T>(List<T> source, Predicate<T> splitWhen)
{
    int i;

    for (i = 0; i < source.Count && !splitWhen(source[i]); ++i)
        ;

    var part2 = source.GetRange(i, source.Count - i);

    source.RemoveRange(i, source.Count - i);

    return part2;
}

Test code for this is very similar:
var list = new List<int>{ 1, 2, 3, 1, 2, 3 };

var part2 = SplitListBy(list, item => item >= 3);

Console.WriteLine(string.Join(", ", list));
Console.WriteLine(string.Join(", ", part2));

(Output is the same as the other test code.)

A: At the time that I'm writing this answer, I don't think that any of the other answers faithfully replicate Haskell's span function. That's okay, you may actually be looking for something else, but I wanted to add this for completion's sake.
First, you can't necessarily assume that span only iterates over the input list once. It's difficult to reason about Haskell's run-time behaviour because of its lazy evaluation, but consider this list:
xs = [trace "one" 1, trace "two" 2, trace "three" 3,
      trace "one" 1, trace "two" 2, trace "three" 3]

Here I've deliberately used trace from Debug.Trace so that we can observe what's going on. Specifically, I want to point your attention to what happens if you iterate over the lists independently, as one would probably do in 'real' code:
Prelude Data.List Debug.Trace> (l, r) = span (< 3) xs
Prelude Data.List Debug.Trace> l
one
[1two
,2three
]

Iterating over the first list stops at the first value that evaluates to False, so that's fine and efficient. That's not the case, however, when you print the second list:
Prelude Data.List Debug.Trace> r
one
two
three
[3,one
1,two
2,three
3]

Notice that while it only prints [3, 1, 2, 3], it iterates over the entire list. How could it do otherwise? It's a function. It doesn't maintain a bookmark over how far it's already iterated the list.
On the other hand, the function does handle infinite lists:
Prelude Data.List> take 10 $ fst $ span (< 3) $ repeat 1
[1,1,1,1,1,1,1,1,1,1]
Prelude Data.List> take 10 $ fst $ span (< 3) $ repeat 3
[]
Prelude Data.List> take 10 $ snd $ span (< 3) $ repeat 3
[3,3,3,3,3,3,3,3,3,3]

As far as I can tell, few of the other answers (as I'm writing this) handle infinite lists.
In C#, lazily evaluated lists are modelled with IEnumerable<T>, so the best I've been able to come up with is this:
public static (IEnumerable<T>, IEnumerable<T>) Span<T>(
    this IEnumerable<T> source,
    Func<T, bool> pred)
{
    return (source.TakeWhile(pred), source.SkipWhile(pred));
}

which, admittedly, is hardly above the Fairbairn threshold. It does, however, handle infinite sequences in the same way as span does:
> var (left, right) = new[] { 1, 2, 3, 1, 2, 3 }.Span(x => x < 3);
> left
TakeWhileIterator { 1, 2 }
> right
SkipWhileIterator { 3, 1, 2, 3 }
> var (left, right) = 1.RepeatInfinite().Span(x => x < 3);
> left.Take(10)
TakeIterator { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
> var (left, right) = 3.RepeatInfinite().Span(x => x < 3);
> right.Take(10)
TakeIterator { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 }
> left.Take(10)
TakeIterator { }

A: the simplest way to use ToLookup
example
var listInt = new List<int>{1, 2, 3, 4, 5, 6};
var result = listInt.ToLookup(x => x > 3);

Result
[[1,2,3], [4,5,6]]
Edit
var listInt = new List<int> { 1, 2, 3, 1, 2, 3 };

Create an extension method
        public static IEnumerable<T> TakeUntil<T>(this IEnumerable<T> source, Func<T, bool> predicate)
        {
            foreach (var item in source)
            {
                if (!predicate(item))
                    break;
                yield return item;
            }
        }

and call it
var first = listInt.TakeUntil(x => x < 3);
var second = listInt.Skip(first.Count());

Result
first = [1,2]
second = [3, 1, 2, 3]

A: I don't think there is a native .NET Framework or .NET Core method that does this, so you'll probably have to write your own. Here is my extension method implementation of this:
public static Tuple<IEnumerable<T>, IEnumerable<T>> SplitWhen<T>(this IEnumerable<T> self, Func<T, bool> func)
{
    // Enumerate self to an array so we don't do it multiple times
    var enumerable = self as T[] ?? self.ToArray();
    var matching = enumerable.TakeWhile(func).ToArray();
    var notMatching = enumerable.Skip(matching.Length);

    return new Tuple<IEnumerable<T>, IEnumerable<T>>(matching, notMatching);
}

This method will return a tuple with tuple.Item1 being the part of the list that matches the predicate, and tuple.Item2 being the rest of the list.
This method needs to be declared in a separate static class as it is an extension method for IEnumerable<T>. You can also use Tuple construction/ deconstruction if you want to name Item1 and Item2 something different

A: I believe you are looking for a c# IEnumerable. You could write for example
IEnumerable<int> list = new List<int> { 1,2,3,4,5,6};
var list1 = list.Where(x=>x>3); //deferred execution
var list2 = list.Where(x=>x<=3); //deferred execution

A: I have accepted  @Matthew Watson solution.Though i will also post a little modified version  using the Span and ReadOnlyMemory
public static (IEnumerable<T>first,IEnumerable<T> second) Span<T>(this ReadOnlyMemory<T> original,Func<T,bool> predicate) {
            List<T> list = new List<T>();

            int splitIndex = 0;
            for (int i = 0; i < original.Length && !predicate(original.Span[i]); i++) {
                list.Add(original.Span[splitIndex=i]);
            }
            var part2 = original.Slice(splitIndex);
            return (list, part2.ToArray());
        }


text:
Q: Convert Esri ASCII grid raster format to GeoJSON I received data as *.asc file. How can I convert the ASCII data into a *.GeoJson file including polygons and the band data? I've tried various approaches with rasterio and gdal but they always returned one of the following errors which I was unable to solve:
CRSError: The EPSG code is unknown. PROJ: proj_create_from_database: Cannot find proj.db
ERROR 4: Unable to open EPSG support file gcs.csv.  Try setting the GDAL_DATA environment variable to point to the directory containing EPSG csv files
The head of my *.asc data looks as follows:
ncols         720
nrows         360
xllcorner     -180.0000
yllcorner     -90.0000
cellsize      0.5000
NODATA_value  -9999

I figures, maybe I can simply draw my own grid of 720*360=259200 cells and assign the values in the *.asc file. However, the file readme suggests the data comprises 67420 cells which I do not really understand.

I can import the data into a np.array() via
import rasterio

src = rasterio.open('data.asc')

data = src.read(1)

The next step would be to create a GeoDataFrame and link the data array.

A: I came up with my own solution.
First of all, I import some packages:
import rasterio
import matplotlib.pyplot as plt
import numpy as np
import geopandas as gpd
import pandas as pd
from shapely.geometry import Polygon

Then, I import the *.asc file and check what bands it contains. I save the band in a DF and create a plot.
src = rasterio.open('data.asc')
print("Bands: " + str(src.indexes))
data = src.read(1)

plt.imshow(data)

The *.asc file has 360 rows and 720 columns. This means I have a raster with grid cells of the size 180/360 * 360/720 = 0.5 * 0.5 arcminutes. I create the corresponding grid via:
stepsize = 0.5 # Degree

lonmin = -180 # X #
lonmax = 180 # X #

latmin = -90 # Y
latmax = 90 # Y

cells = int((latmax*2*1/stepsize)*(lonmax*2*1/stepsize))

i = 0
stepsize = int(stepsize*2) # Avoid float numbers in for loops
grid = gpd.GeoDataFrame(index=range(cells), columns = ['count','geometry'])

for y in range(latmin*2, latmax*2, stepsize): # For all rows Y
    for x in range(lonmin*2, lonmax*2, stepsize): # For all columns X

        # Create square/grid cell
        a = (stepsize/2+(x**stepsize/2),y*(-1)*stepsize/2) # Start at
        b = (stepsize/2+(x**stepsize/2),y*(-1)*stepsize/2-stepsize/2)
        c = (stepsize/2+(x**stepsize/2-stepsize/2),y*(-1)*stepsize/2-stepsize/2)
        d = (stepsize/2+(x**stepsize/2-stepsize/2),y*(-1)*stepsize/2)

        cell = gpd.GeoSeries([Polygon([a,b,c,d])])

        grid['geometry'][i] = cell[0]
        grid['count'][i] = i
        i = i + 1

Since my grid is saved in a one-dimensional GeoDataFrame, I also turn the ASCII data into GeoDataFrame of the same dimension:
ascii_onedim = pd.DataFrame(columns = ['band_1'])

for x in range(360): # For all rows
    temp = pd.DataFrame(data[x:x+1])
    for y in range(720): #For all columns
        ascii_onedim = ascii_onedim.append({'band_1': temp.iloc[0,y]}, ignore_index=True)
del temp

I also introduce a "count" column, so that I have a key for concatenating both dataframes.
ascii_onedim = ascii_onedim.reset_index()
ascii_onedim.columns=['count','band1']

Concatenating
final = pd.concat([ascii_onedim, grid], axis=1)

Somehow, the geometries are not recognized as such. I fix this via:
final = final.set_geometry('geometry')

Then, I plot:
final.plot(column='band1')

I successfully turned the data from the *.ascii file into a GeoDataFrame which I can save via grid.to_file('filename.json', driver='GeoJSON').
I am not great with Python so please forgive me the style of code. I am sure, there are nicer way to achieve the same results.