text:
Q: Flink keyBy POJO (Apologies for the inevitably terrible formatting as I'm posting from my phone)
I am doing a keyBy and then an aggregate but Flink is not grouping the data correctly (instead each event falls into its own group by).
Example:
Class Purchase {
    String product;
    Integer quantity;
}

Class Filter {
    String product;

    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((product == bull) ? 0 : displayName.hashCode());
}

Class FilteredPurchase {
    Filter filter;
    Purchase purchase;
}

DataStream<FilteredPurchase> =
    ...
    .keyBy("filter") //This works
    .keyBy(x -> x.getFilter()). // This doesn't
    .sum("trade.quantity");

If we consider the case of a stream that looks like:
[
    {"filter": {"product": null}, "purchase": {"product": "apple", "quantity": 10},
    {"filter": {"product": null}, "purchase": {"product": "apple", "quantity": 10},
    {"filter": {"product": "apple"}, "purchase": {"product": "apple", "quantity": 10},
    {"filter": {"product": "apple"}, "purchase": {"product": "apple", "quantity": 10},
]

I would expect it to be keyed into 2 partitions (because there are two filters) the total in each being 20. However, I actually end up with 4 partitions each with a total of 10.
Interestingly, if I use the field expression version it does do what I want, but I would like to keep everything as a POJO as I intend on doing some more with it later on.
Am I missing something here? Can a KeySelector return a POJO?

A: First question is why you don't just use the product (String) as your key, since that's all you've got in the Filter class. So
.keyBy(x -> x.getProduct())
But in any case, I think your key class (Filter) has to implement the equals() method.


text:
Q: R Data Merge without Copying In data.table, it is possible to work directly on the current data table (say DT) without creating a copy of it. For example, this can be done when creating a new column.
DT[,new_col:=1]

I would like to know how this can be done for merging, in particular left join. For example, the data table way of left join is
DT_right[DT_left,on="id"]

However, this does not modify the original DT_left table, requiring me to reassign. i.e.
DT_left = DT_right[DT_left,on="id"]

Is there a way for me to do this without reassigning? i.e. working on DT_left directly.

A: Lets say you have DT_right as
     id right_value
  1:  1           2
  2:  2           4
  3:  3           6
  4:  4           8

and DT_left as
    id left_value
 1:  1          3
 2:  2          6
 3:  3          9
 4:  4         12

if you want to perform left-join of DT_left on DT_right then i.value will be i.left_value i.e. the column name of the column you want to join from DT_left to DT_right.
DT_right[DT_left, joined_from_left := i.left_value, on = "id"]
DT_right[]
   id right_value joined_from_left
1:  1           2                3
2:  2           4                6
3:  3           6                9
4:  4           8               12

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can you please explain this—"the rules involving mixed types of operands do not apply to the shift operators" I can't understand the line "The result of the shift has the same type as the thing that got shifted (after the integral promotions)" in the following extract from the C book by Mike Banahan (Section 2.8.2.3).

Importantly, the rules involving mixed types of operands do not apply
  to the shift operators. The result of the shift has the same type as
  the thing that got shifted (after the integral promotions), and
  depends on nothing else.

If something is already promoted to an integer (as required during shift operator use), then how can it be converted back to the same type as it originally had, unless of course it is on the right side of an assignment and is being assigned to a variable of the same type as it had before integer promotion? Further, what exactly does the line "the rules involving mixed types of operands do not apply to the shift operators" signify?
Please shed some light on both parts of the question. Thank you.
The following are screenshots from the book, relating to promotions during use of bit-wise operators and during mixed expressions in general, respectively.

A: It is pretty straight forward; the type of the result of a shift operation is the type of the LHS operand.  For most binary operators, the result is based on both the LHS and RHS operands, but the shift operators are different.
unsigned char      uc = 0x08;
unsigned short     us = 0x0008;
unsigned int       ui = 0x00000008;
unsigned long long ul = 0x0000000000000008;

(I'm assuming sizeof(unsigned int) == 4 for this answer.  The details have to change if it is different, but the concepts remain unchanged.)
Now consider some expressions:
uc + uc;

Both types are converted to int and the result is int.
us + us;

Again, both types are converted to int and the result is int.
us + ui;
ui + us;

The value in us is converted to unsigned int and the result is unsigned int (note that the previous values were converted to signed int aka int).
ui + ul;
ul + ui;

Both of these expressions convert ui to an unsigned long long and the result is unsigned long long.  Note that these expressions are symmetric; the type of the result (and, indeed, with the + operator, the value of the result) does not depend on which value is on the LHS and which on the RHS of the operator.
So much for the ordinary operations; now what about shifts?
uc << uc;

The LHS is converted to int by the usual arithmetic conversions and the result is an int.
us << us;

This result is also an int.
ui << ui;

This result is an unsigned int.
ul << ul;

This result is an unsigned long long.  But what about mixing the types up?
uc << ul;   // Result: int
ul << uc;   // Result: unsigned long long
us << ui;   // Result: int
ui << us;   // Result: unsigned int
ui << ul;   // Result: unsigned int
ul << ui;   // Result: unsigned long long

The promoted type of the LHS operand controls the type of the result.  For the types shorter than int, the result is int; for the other types, the type is the type of the LHS operand.
That's all your quote means.


text:
Q: Navigate to mainpage after clicking app in share option list? I am trying to navigate back to my mainpage after clicking my app in share option list.
This is my main page: https://gyazo.com/831db63433d9b3e2051ed605dc3489af
When i click my app in the share option list here: https://gyazo.com/47234162530078e1a83cdfb17eaf5401
I come to this page: https://gyazo.com/11cfb0f6818127e2cd4ef51d5ed970b9
But i want to navigate to picture 1 when i click my app in the share option list. How can i do this? The share intent activity is in the AndroidManifest.xml as you see on the picture. The page that is shown in picture one is called "TabbedPagePage" and that is the page i am trying to get to in the first place, without getting to this ugly, no content dark picture.

A: It seems you need to set the IntentFilter for your MainActivity instead of use another activity.
And it will navigate to main page eventually.
For example:
    [Activity(Label = "Navigatetomainpage", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    [IntentFilter(new[] { Intent.ActionSend }, Categories = new[] { Intent.CategoryDefault }, DataMimeType = "image/*", Label = "Navigatetomainpage")]
    [IntentFilter(new[] { Intent.ActionSend }, Categories = new[] { Intent.CategoryDefault }, DataMimeType = "text/plain", Label = "Navigatetomainpage")]
    [IntentFilter(new[] { Intent.ActionSendMultiple }, Categories = new[] { Intent.CategoryDefault }, DataMimeType = "image/*", Label = "Navigatetomainpage")]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle bundle)
        {
            Intent intent = Intent;
            String action = Intent.Action;
            String type = intent.Type;

            if (Intent.ActionSend.Equals(action) && type != null)
            {
                if ("text/plain".Equals(type))
                {
                    // Handle text being sent
                    // ...
                    // ...
                    // ...
                }
                else if (type.StartsWith("image/"))
                {
                    // Handle single image being sent
                    // ...
                    // ...
                    // ...
                }
            }
            else if (Intent.ActionSendMultiple.Equals(action) && type != null)
            {
                if (type.StartsWith("image/"))
                {
                    // Handle multiple images being sent
                    // ...
                    // ...
                    // ...
                }
            }
            else
            {
                // Handle other intents, such as being started from the home screen
            }

            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

            global::Xamarin.Forms.Forms.Init(this, bundle);
            LoadApplication(new App());
        }
    }


text:
Q: How to update windows time zones list? I have front-end and back-end systems using the System.TimeZoneInfo for retrieving Timezone by ID.
There are several time-zones missing from the back-end machine (running windows Server 2012) and I'm not sure how to get an update.
For instance "Line Islands Standard Time"
Using System.TimeZoneInfo.FindSystemTimeZoneById(String id) I'm getting this exception
System.TimeZoneNotFoundException: The time zone ID 'Line Islands Standard Time' was not found on the local computer.
Both systems have .net framework 4.8 installed.


text:
Q: Sending a PNG using HTTP in C#

I'm developing my own simple webserver in C#, and I have normal html files and subfolders etc in place and working fine... however my issue lies with sending PNG files.
Once the browser has made the HTTP request and my other code has done its magic, I need to send a response header. Here is my code to do this:
        else if (URL.EndsWith(".ico") || URL.EndsWith(".png"))
        {
            if (File.Exists(Program.Start_Directory + URL))
            {
                byte[] ImgFile = File.ReadAllBytes(Program.Start_Directory + URL);
                sw.Write("HTTP/1.0 200 OK\r\n");
                sw.Write("Content-Type: image/png\r\n");
                sw.Write("Content-Length: " + ImgFile.Length + "\r\n");
                sw.Write("\r\n");
                sw.Write(ImgFile);
            }
            else
            {
                FileNotFoundPage(sw);
            }
        }

sw in this instance being the StreamWriter for the socket connection to the browser.
When I run this, the browser screen goes black like it usually does when its about to load an image, but no image loads and the spinning loading wheel remains spinny indefinitely.
How can I get this to work? Thanks.

A: Things get messy when you use a StreamWriter (which is designed to write strings with a specific Encoding to a stream) with binary data.
It looks like you are invoking this overload of StreamWriter.Write with the belief that it writes the bytes verbatim to the output stream. The docs state that this overload actually...

Writes the text representation of an object to the text string or stream by calling the ToString method on that object

You have two options. Carry on using StreamWriter and Flush, then write the binary data directly to the underlying stream:
byte[] ImgFile = File.ReadAllBytes(Program.Start_Directory + URL);
sw.Write("HTTP/1.0 200 OK\r\n");
//...etc
sw.Flush();
sw.BaseStream.Write(ImgFile,0,ImgFile.Length);

or just do everything in bytes:
var sb=new StringBuilder();
sb.AppendLine("HTTP/1.0 200 OK");
//...etc
var headerBytes = Encoding.ASCII.GetBytes(sb.ToString());
Stream str = iGotTheStreamFromSomewhere;
str.Write(headerBytes,0,headerBytes.Length);
str.Write(ImgFile,0,ImgFile.Length);


text:
Q: how to remove the class from parent div in keyup using react js I am having set of form fields, when i click on the submit button i adding error message class for each input textbox parent div this all are working fine,
my problem is when i keyup the textbox i need to remove the error message class using reactjs

     <input type="text" required />

my div structure is like this, for validation i am using npm validator module

A: So with the limited data provided in the question, this should give you some direction.
Declare a state for the state change on the keyUp:
 var state = {
      isKeyUp: false,
 }

updateKeyUpState() {
  this.setState( function( prevState) {
    return {
      isKeyUp: !prevState.isKeyUp
    }
  })
}

Your Render function:
render() {
    <button type="submit" onkeyup={updateKeyUpState}> SUBMIT </button>

         <input type="text" required />

}

A: Try this
function getCompState(){return {keyUp : false}}
 class Example extends React.Component{
     constructor(props){
       super(props)
       this.state = getCompState();
     }
     render(){
      var class_new = 'error-msg';
      if(this.state.keyUp ){
       class_new = 'class_new_defined'
      }
        return(

           <input type="text" required />

        )
     }
   }
Css
.class_new{}


text:
Q: 500 Internal error server when I use @Query in Spring data rest 2.0.0 I am trying to upgrade an application made with Spring data rest 1.0.0 to Spring data rest 2.0.0. The problem is with a method which gives me the result of a count query. This method works fine in the first version but, when I run the second version, I get, in my browser, a 500 error. I'm not getting more error log. The log of the server is not tell me anything and the application is not throwing any exception.
This is the code of my repository:
public interface FilmRepository extends PagingAndSortingRepository <Film,Long>{

public Page<Film> findByTituloContains(@Param("titulo") String titulo, Pageable pageable);

@Query("Select count(*) "+
        "From peliculas p inner join p.castFilm r"
        + " WHERE p.id=:id")
public Long numOfActors(@Param("id") Long id);

}
This is the unique method with the "@Query" annotation. The others methods are working fine. The funny thing is that I coded a JUnit to test this method and it gives me the right result without errors.
My server is a Tomcat 7.0.41. Any idea?

A: The fact that you are not getting much in the log suggests that the request may not be even reaching the controller. Try setting your log level to DEBUG and see if it even gets into Spring Data Rest code. The next step would be to just run Tomcat in debug mode and step into the code to see where the request gets rejected.


text:
Q: Fixed Root Node for CatBoost/ XGBoost? Set Root Node for CatBoost / Xgboost
Dear all,
My team are facing with a problem when using CatBoost / XGBoost. We want to set the first root for our algorithms but it seem impossible. Are there any way to solve this problems?
For example, our dataset have 100 features: A1, A2, .... A100. And we want to set the root node in every trees is feature A1 (binary feature).
Thank you.


text: Q: Can .net core 5.0 API start a winform UI applicaiton Is it possible to have a .net core 5.0 API start a Winform UI?  If so how? In VS it works when I use kestrel; but in IIS the winform process is running without the UI being visible.  I need to run the  winform tester application on local windows 10 workstation.  The tester application is to fire off when it receives a web request message. Have had seemlier issue attempting to accomplish the objective with a window service.  Process runs, but no UI.  Any advise would be appreciated...


text:
Q: Add style-name to table of content in QGIS 2.18 There is a possibility to add multiple styles to one layer.
Is there a way to add the style-name to the layername in the TOC, changing when you change to another style?


text:
Q: How to find a source file used in process.binding('..') in node source code? I want to see source code of the file mentioned in process.binding() statement in nodeJS source code, have seen similar question on stackoverflow but most of them answers to specific cases like fs etc.
I want explanation based on which I should be able to find any file mentioned in process.bindings().

A: Since this question is lying here for very long I decided to give it another try to find the answer and found one very nice presentation online.
Process.bindings presentation
To summaries this, process.bindings() binds the javascript object with the C++ object which exposes the C++ functions to be executed from javascript, essentially it creates a javascript wrapper around the C++ functions to make it available from NodeJS.
To find which C++ function is bound to which javascript function you can dig into NodeJS source tree here NodeJs source tree . Names are straightforward to map with core module names and look for signature  env->SetMethod(target, "<modulename>", <C++ function name>);
Example:  env->SetMethod(target, "stat", Stat);


text:
Q: DJI lightbridge 2 remote controller I want to develop a simulator using DJI lightbridge 2 remote controller .I  want to connect DJI Controller lightbride 2 remote controller with Android. I only want to read its control stick / buttons data and want to use in my Android app.

A: Maybe below link is what you need.
https://developer.dji.com/api-reference/android-api/Components/RemoteController/DJIRemoteController_DJIRCHardwareState.html


text:
Q: Java - How to navigate to a map url in android studio? I have a button that navigates to the map with a certain link. Here is my code:
Intent open2 = new Intent(android.content.Intent.ACTION_VIEW);

open2.setData(Uri.parse("https://www.google.com.eg/maps/dir/''/point+90+mall+location/data=!4m5!4m4!1m0!1m2!1m1!1s0x145822591a17706b:0xc9f886adcffbb941?sa=X&ved=0ahUKEwiF5-KS6t3SAhWoLcAKHWI-CEoQ9RcIeTAM"));

startActivity(open2);

But when I click from my mobile, it goes to the map. But it gives this to me:

Cannot find the starting point

How can I fix that?

A: You are using the wrong maps query-string, try this:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?q=Point 90 Mall, Cairo Governorate"));
startActivity(intent);

Generally use this query http://maps.google.com/maps?q=PLACE_NAME where you replace the PLACE_NAME with the place name (or search string) of google maps.
More info here: https://developers.google.com/maps/documentation/android-api/intents
and here:
open google maps through intent for specific location in android


text:
Q: Modern Core Data Performance with UUID I have a Core Data application with:

*

*549 Account entities with myJournals relationship (one to many)

*24000 Ledger entities with myJournals relationship (one to many)

*57000 Journal entities with myAccount and myLedger (one to one) inverse
relationship

Each entity has a uuidKey string attribute with a UUID string imported from an online database.
I'm trying to run the app on an iPhone 5S. Inserting objects is relatively fast, but finding and linking the relationships is longer than anticipated.
let debugTime = NSDate()
let thisRequest = NSFetchRequest(entityName: "Ledgers")
let keyLeft = NSExpression(forKeyPath: "uuidKey")
let keyRight = NSExpression(forConstantValue: ledgerKey)
let keyPredicate = NSComparisonPredicate(leftExpression: keyLeft, rightExpression: keyRight, modifier: NSComparisonPredicateModifier.DirectPredicateModifier, type: NSPredicateOperatorType.EqualToPredicateOperatorType, options: NSComparisonPredicateOptions.allZeros)
thisRequest.predicate = keyPredicate
thisRequest.fetchBatchSize = 1
thisRequest.fetchLimit = 1
println("DEBUG COMMENT: \(debugTime.timeIntervalSinceNow) time to create thisRequest.")
var keyError: NSError? = nil
if let keyArray = self.managedObjectContext!.executeFetchRequest(thisRequest, error: &keyError) {
    if keyArray.isEmpty {
        myLedger = nil
    } else {
        if let thisLedger = keyArray[0] as? Ledgers {
            println("DEBUG COMMENT: \(debugTime.timeIntervalSinceNow) time to find thisLedger.")
            myLedger = thisLedger
        } else {
            myLedger = nil
        }
    }
}
println("DEBUG COMMENT: \(debugTime.timeIntervalSinceNow) time to link myLedger.")

I get log times like this:
DEBUG COMMENT: -9.20295715332031e-05 time to create thisRequest.
DEBUG COMMENT: -0.174275994300842 time to find thisLedger.
DEBUG COMMENT: -0.174659013748169 time to link myLedger.
DEBUG COMMENT: -0.00464397668838501 time to find and link myAccount.

0.092 milliseconds to create the NSFetchRequest is fine.
174 milliseconds to find the Ledger? On an indexed UUID string when there are 24k Ledgers?!? When I need to link this to 57k Journals?
Faster is always better. 4 milliseconds to find a link myAccount when there are 549 accounts is slightly disappointing but acceptable. For the Ledger search I was expecting about 25-50 milliseconds, not 174!
I'm running this in its own core data store and context:
    // Initialize the persistent store coordinator for the sync session.
    let url = appDel.applicationDocumentsDirectory.URLByAppendingPathComponent("FoodyCoreModel.sqlite")
    self.syncStore = NSPersistentStoreCoordinator(managedObjectModel: appDel.managedObjectModel)
    var error: NSError? = nil
    var failureReason = "There was an error creating or loading the application's saved data."
    let storeOptions: [NSObject: AnyObject] = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
    self.syncStore.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: storeOptions, error: &error)

    // Initialize the managed object contextfor the sync session
    self.syncContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType)
    self.syncContext.persistentStoreCoordinator = self.syncStore
    let nmp = NSMergePolicy(mergeType: NSMergePolicyType.MergeByPropertyStoreTrumpMergePolicyType)
    self.syncContext.mergePolicy = nmp

Is this reasonable performance to expect with an iPhone 5S? I've read many of the Core Data performance questions here, but many of them date from years ago. I was hoping that iOS 8 and more recent devices would be significantly faster. I'm not trying to do a MATCHES or CONTAINS search, just EQUALS on an indexed text field!
I've read the  Core Data Performance Guide. Is there something I'm missing or am I just expecting too much from a mobile device?

A: The most likely slowdown in your code is that you're fetching Ledger instances one at a time, and you say there are 24,000 of them. That's going to be a major bottleneck no matter what. Fetching is a relatively expensive operation, regardless of whether you're using a string ID in the predicate, so your code is going to be spending most of its time fetching.
You should be fetching in batches instead of one at a time. Collect 50 or 100 or so uuidKey values into an array and use a predicate format like "uuidKey in %@" with the array as the substitution variable. Process that batch, and repeat until done.
For more detail on how to import data efficiently, refer to Apple's "Efficiently Importing Data" guide, especially the section called "Implementing Find-or-Create Efficiently".
As an aside, using println like this is a really poor way to measure performance. Use Instruments. It'll give you more detail with less overhead and without cluttering up your code, and will help you nail down exactly where bottlenecks are.


text:
Q: Auto results search form jquery I would like to have a search form (with more than one field) that would display the avaible results as the person types the value, geting these values from my database.
Doing some research I found the code below, but as you can see it works with words pre-defined by hand, and not using a database to recover values like I want.
Is there a way I can change this code, maybe the script, to achieve the result I want?
<head>
<script>
$(function() {
    var availableTags = [
        "ActionScript",
        "AppleScript",
        "Asp",
        "BASIC",
        "C",
        "C++",
        "Clojure",
        "COBOL",
        "ColdFusion",
        "Erlang",
        "Fortran",
        "Groovy",
        "Haskell",
        "Java",
        "JavaScript",
        "Lisp",
        "Perl",
        "PHP",
        "Python",
        "Ruby",
        "Scala",
        "Scheme"
    ];
    $( "#tags" ).autocomplete({
        source: availableTags
    });
});
</script>
</head>

<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
</body>

A: you can see these two links
http://jqueryui.com/autocomplete/#remote-jsonp
http://jqueryui.com/autocomplete/#remote
if you are using php
http://www.simonbattersby.com/blog/jquery-ui-autocomplete-with-a-remote-database-and-php/
http://burnmind.com/howto/how-to-feed-jquery-uis-autocomplete-with-a-database-generated-dataset
if you are using asp.net
http://www.dotnetcurry.com/ShowArticle.aspx?ID=515
http://www.aspsnippets.com/Articles/Using-jQuery-AutoComplete-Plugin-in-ASP.Net.aspx

A: You need to use remote data source
$( "#tags" ).autocomplete({
        source: "specify_url_to_your_server_here"
    })

http://jqueryui.com/autocomplete/#remote
And of course you need some server-side to support this.


text:
Q: How to solve Symfony error Variable "expanded" does not exist? Currently, I develop an app with PHP Symfony Framework. I've got a problem with Form Builder (I think).
I have two entities. Question and Choice.
Question and Choice are OneToMany Relationship Entity. One Question has many Choice.
Another two entities, Video and Category, the relationship is just the same with Question and Choice.
I create scaffolding crud for those entity with php bin/console make:crud.
Then I add the relationship symfony like in this guide from Symfony.
The logic is, I must select the Category first to create new Video. Same with the Choice, I must select the Question first to create new Choice data.
My problem appear when I open the Choice Create Form [/choice/new]. It says

Variable "expanded" does not exist.

Then the error details show on this lines
return $this->render('choice/new.html.twig', [
    'choice' => $choice,
    'form' => $form->createView(), // The highlighted error appear on this line
]);

But, It just happen in the Question-Choice, My Category-Video relationship is just fine. I tried to make Question-Choice as same as Category-Video (I changed the name of the entity for sure), I triple check it, but the error on Choice Create Form still occur.
This is my App\Form\ChoiceType
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('content')
        ->add('letter')
        ->add('image')
        ->add('question', EntityType::class, [
            'class' => Question::class,
            'choice_label' => 'content'
        ])
    ;
}

Notice the add('question')
and this is my App\Form\VideoType buildForm method
<?php
public function buildForm(FormBuilderInterface $builder, array $options)
{

    $builder
        ->add('title')
        ->add('url', FileType::class, [
            'label' => 'Video File',
            'required' => false,
        ])
        ->add('thumbnail', FileType::class, [
            'required' => false,
        ])
        ->add('description')
        ->add('category', EntityType::class, [
            'class' => Category::class,
            'choice_label' => 'name'
        ])
    ;
}

Notice the add('category')
So, anyone know what is happening?

A: I renamed App\Form\ChoiceType to App\Form\TheChoiceType, make some adjusment for class name changing on the controller. Everything is work!
I don't believe this! The solution is to rename the form type.


text:
Q: In powershell, how can I define all env vars for the next command similar to python's Popen abilities? In powershell, how can I...

*

*explicitly define all the env vars for the next command?

*I don't want any system env vars if possible,

*After this command runs I dont want anything we have done to affect further processes in the shell.

As an example, in python we have the equivalent ability in Popen to pass a dictionary of the full environment to the subprocess, and I'm hoping there might be something similar in Powershell.

A: I think this link explains what you need: Windows user environment variable vs. system environment variable
[Environment]::GetEnvironmentVariable("TEMP", "Machine")


text:
Q: Get machine name from registry using RegQueryValueEx I am trying to do an application which shows machine name of the PC fetch from registry. It has to run in 64 bit window 7 machine.
But I can only manage to output the system error message.
In below code,
I always get value of value1str (using RegOpenKeyEx method) => as 0 (which is ERROR_SUCCESS)
and value2str (using RegQueryValueEx method) => as 2 (which is ERROR_FILE_NOT_FOUND)
Anyone knows how to display the real machine name?
Please help!
#define KEY_WOW64_64KEY (0x0100)
#include <iostream>
#include <string>

BEGIN_MESSAGE_MAP(CPOConLogApp, CWinApp)
END_MESSAGE_MAP()

CPOConLogApp::CPOConLogApp()
{
    int value1;
    int value2;
    HKEY root = NULL;
    CString value1Str,value2Str;

    value1=RegOpenKeyEx( HKEY_LOCAL_MACHINE, TEXT("SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ActiveComputerName"), NULL, KEY_READ|KEY_WOW64_64KEY, &root);

    value1Str.Format("%d",value1);

    MessageBoxA ( NULL, value1Str, "Test", MB_OK );

    LPBYTE data = NULL;
    DWORD dwType;
    DWORD dwSize;
    data = new BYTE[dwType];

    value2=RegQueryValueEx(HKEY_LOCAL_MACHINE,TEXT("Computer Name"), NULL, &dwType, data, &dwSize);

    value2Str.Format("%d",value2);

    MessageBoxA (NULL, value2Str , "Test", MB_OK );

}

A: Alternative solution:
Instead of trying to find where is the key in the Registry and how to read it, you can just rely on the API Microsoft provide.
To get the Computer NetBIOS name (initialized from registry at system startup) use GetComputerName like below.
#include <windows.h>

int main()
{
char buf[1024];
DWORD dwCompNameLen = 1024;

if (0 != GetComputerName(buf, &dwCompNameLen)) {
    printf("name %s\n", buf);
}

return 0;
}

A: You can read the computer name from the below mentioned registry key,

System\CurrentControlSet\Control\ComputerName\ComputerName

A: I found out why always ERROR_FILE_NOT_FOUND value. I suppose to put last parameter of RegOpenKeyEx to the first parameter in RegQueryValueEx. It should be like this.
value2=RegQueryValueEx(root,TEXT("Computer Name"), NULL, &dwType, data, &dwSize);

If you want prompts the value of the registry, computer name in this case, use the below code.
value.Format("%s",pszBuffer);
MessageBoxA (NULL, value , "Test", MB_OK );


text:
Q: data migration takes long time
I have been written an c# console app for migrate data;

count of records not so more; each table has almost 100 hundred records. but the structure of data and the businesses logic is so complicated with almost 200 tables.

my data migration has all types of actions: delete, update, insert, get.

delete and update operation just use for data correction in source database

now my migrate data takes so long time; almost three days or more!

some actions for improvement:

1- at first set 'NOCHECK CONSTRAINT' in source database; when this operation do it: delete, update and insert.

2- then for fetch data from source database; set some index.

3- disable all index and constraint in destination database when insert data.
now can any one suggest a solution for improvement duration time?
It should be noted that in this phase of the project I couldn't switch to another solution for example SSIS. I must be improvement this console app!.
 be used EFCore 2.2 with pure query for transfer data;
thanks a lot

A: I had a very significant performance improvement by switching recovery model from Full to Simple. Obviously, there are good reasons to use Full; but depending on the changes that your migration is doing, the performance improvement may be order of magnitude!
Sorry to bring it up, but it is very difficult to understand what you are trying to say (I suppose it is due to poor English). Maybe run some grammar checker to improve clarity! Is your question about EF Migrations? Or you are using a custom query to read data from one DB and write into another? It seems the latter, then you probably need to look at the SQL extended events to identify poorly written queries before you start tuning the database instance! Nothing improves performance like tuning the SQL!


text:
Q: Take existing project and move it into a Ruby on Rails environment I have the front end of a website built.  It is made from a number of HTML, JavaScript, and Jquery files.  Is there a way to take those files and move them into a Ruby on Rails environment so that I don't need to remake everything?

A: Sure. Create a new rails app (rails new app-name). Copy your existing javascript files into the Rails project at public/javascripts/. Your views/html are a bit more dependent on how you want to grow.
One option is to create a single PagesController and not bother with resources/models/etc, and you would just put all of your "views" into /app/views/pages/. You don't even have to rename them to .html.erb like you would conventionally see — you can leave them as just plain html. Your routes.rb file would look something like this:
get '/:action', :controller => 'pages', :as => 'page'

Which would afford you routes like "example.com/hello_world" that would route to PagesController#hello_world, rendering "app/views/pages/hello_world.html". If you want to use ERb, you can add that ".erb" suffix to your view file and then you can use the page_path helper to assemble links:
<%= link_to 'Hello World Demo', page_path('hello_world') %>

You will still probably want to extract the common elements into a layout at app/views/layouts/application.html.erb (again, the ERb being optional).

Another route would be to actually separate your application into resources. If you have a page that lists books, for example, you could create a BooksController and put the relevant view under app/views/books/index.html. This doesn't make sense to do if you're not going to provide some additional functionality in the future, though.


text:
Q: Check if array can be converted to int then convert laravel I have an array collection that I converted to array using toArray(). Which changes all items to a string. I want to check every item that can be converted to an integer/decimal. The array looks like this
['first_name'] => 'Jake',
['last_name'] => 'Doe',
['age'] => '13', (Change this to an integer/decimal)
['address'] => 'Ivory Street'
['allowance'] => '3000' (Change this to an integer/decimal)

I'm using Laravel/Livewire

A: So many ways to convert int or float. This is the logic :
$data = collect([
    'first_name' => 'Jake',
    'last_name' => 'Doe',
    'age' => '13',
    'address' => 'Ivory Street',
    'allowance' => '3000',
    'float?' => '0.6'
])
->map(function($item){
    return (is_numeric($item))
        ? ($item == (int) $item) ? (int) $item : (float) $item
        : $item;
})
->toArray();

dd($data);

Result :
array:6 [
  "first_name" => "Jake"
  "last_name" => "Doe"
  "age" => 13
  "address" => "Ivory Street"
  "allowance" => 3000
  "float?" => 0.6
]


text:
Q: Salvage Oink logs in Rails.logger format A few weeks ago we installed Oink to analyze the poor memory performance of our Rails application. Unfortunately, we missed the boat on using the Hodel 3000 Compliant logger. After having a catastrophic memory event where we started paging 700 mb into swap, I went to the Oink analyzer only to realize it could not parse our logs in the current default Rails logger format.
Oink log entry in current format:
524072923066355726  2015-04-12T23:29:07 2015-04-13T00:45:44Z    7477731 myapp   54.82.73.66 Local7  Info    app/web.4   Oink Action: messages#create
524072923066355727  2015-04-12T23:29:07 2015-04-13T00:45:44Z    7477731 myapp   54.82.73.66 Local7  Info    app/web.4   Memory usage: 614136 | PID: 12
524072923070550016  2015-04-12T23:29:07 2015-04-13T00:45:44Z    7477731 myapp   54.82.73.66 Local7  Info    app/web.4   Instantiation Breakdown: Total: 1 | User: 1
524072923070550017  2015-04-12T23:29:07 2015-04-13T00:45:44Z    7477731 myapp   54.82.73.66 Local7  Info    app/web.4   Oink Log Entry Complete

Oink log entry in desired Hodel 3000 format.
Apr 12 23:29:07 4598489-yygjkg-2345 rails[12]: Oink Action: messages#create
Apr 12 23:29:07 4598489-yygjkg-2345 rails[12]: Memory usage: 614136 | PID: 12
Apr 12 23:29:07 4598489-yygjkg-2345 rails[12]: Instantiation Breakdown: Total: 1 | User: 1
Apr 12 23:29:07 4598489-yygjkg-2345 rails[12]: Oink Log Entry Complete

Is there any way I can salvage it? Does the top one even have all the necessary information?

A: Once I found the format_message method in the Hodel 3000 compliant logger and realized that Oink was printing the PID in every Oink entry if not on every line, I decided to just reformat the logs with a script. If anyone else has this problem, you can use my script at https://github.com/NealJMD/oinkify/tree/master


text:
Q: click and show all the records in my list in Angular When you press this button you should load the data and then show in the list. I'm using the ng-click and ng-repeat functions.
What is the correct way to declare the functions inside the script? I think that's where I'm failing.

RODRIGO

            <button ng-click="myClick()" class="form-control">Count</button>
            <button ng-click="myClickList()" class="form-control">List</button>

{{count}}

            Id
            Name
            Credit
            Semester

          {{s.id}}

          {{s.name}}

          {{s.credit}}

          {{s.semester}}

RODRIGO

My full example is here

A: Angularjs value is one of provider recipe. Registered value can be accessible via injecting it factory function. Inject studentInfo that inside your controller factory function to get hold on desired values.
app.controller('myCtrl', ['$scope', 'studentInfo', //< -- injected here
  function($scope, studentInfo) {

    ......

  }
]);

Forked Codepen


text:
Q: Как сделать асинхронный ответ в Django? Необходимо отдать 204 ответ сервера не дожидаясь выполнения подпрограммы (django v3.1.5). Попытался сделать через asyncio
views.py
@sync_to_async
@csrf_exempt
@async_to_sync
async def product_update(request):
    if request.method == 'POST':
        loop = asyncio.get_event_loop()
        loop.create_task(do_somthing())

        print('---------------- 1 ----------------')
        return HttpResponse(status=204)
    else:
        HttpResponseForbidden()

async def do_somthing():
    await asyncio.sleep(5)
    print('---------------- 2 ----------------')

Но так не выполняется функция do_somthing(), в консоле только:
---------------- 1 ----------------
[16/Feb/2021 18:00:12] "POST /api/test/update/ HTTP/1.1" 204 0

A: Как вариант, взять какой-нибудь асинхронный фреймворк. Например, dramatiq (есть удобная имплементация - django_dramatiq - https://github.com/Bogdanp/django_dramatiq)
tasks.py
import dramatiq

@dramatiq.actor
def do_somthing():
    print("Async task")

views.py
@csrf_exempt
def product_update(request):
    if request.method == 'POST':
        do_somthing.send()
        return HttpResponse(status=204)
    else:
        HttpResponseForbidden()


text:
Q: Apache poi write big excel files to disk I need to open, alter and write an excel file. As the altering process is a bit more complex I'll leave it out, as the issue does not lie within it. The issue I am running into is while writing the file to disk. The issue starts with files at around 7MB size (doesn't matter if its formula or values).
I prepared following MVCE:
public static void main(String[] args) throws EncryptedDocumentException, IOException, InvalidFormatException {
    String filePath = "C:\\temp";
    String outputFilePath = "C:\\temp\\test";
    ZipSecureFile.setMinInflateRatio(0);
    File f = new File(filePath, "Test.xlsx");
    try (XSSFWorkbook workBook = new XSSFWorkbook(f)) {
        System.out.println("writing file");
        File outputFile = new File(outputFilePath, f.getName());
        try (FileOutputStream fos = new FileOutputStream(outputFile)) {
            workBook.write(fos);
        }
        workBook.close();
    }
    System.out.println("fin");
}

This code already causes the issue I am running into. The exact stacktrace is:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Arrays.java:3236)
    at java.io.ByteArrayOutputStream.toByteArray(ByteArrayOutputStream.java:191)
    at org.apache.poi.openxml4j.opc.internal.MemoryPackagePartOutputStream.flush(MemoryPackagePartOutputStream.java:76)
    at org.apache.poi.openxml4j.opc.internal.MemoryPackagePartOutputStream.close(MemoryPackagePartOutputStream.java:51)
    at org.apache.poi.xssf.usermodel.XSSFSheet.commit(XSSFSheet.java:3575)
    at org.apache.poi.ooxml.POIXMLDocumentPart.onSave(POIXMLDocumentPart.java:462)
    at org.apache.poi.ooxml.POIXMLDocumentPart.onSave(POIXMLDocumentPart.java:467)
    at org.apache.poi.ooxml.POIXMLDocument.write(POIXMLDocument.java:236)
    at test.TestWriteOriginalWorkbook.main(TestWriteOriginalWorkbook.java:25)

Though the trace itself varies from file to file, the exception itself stays the same all the time.
As far as I know, the only way to solves this, would be to increase the available memory for the application. Though if possible, I would like to avoid that. I just checked for my MaxHeapSize which defaults to around 260MB which seems quite low. So an increase to 1GB would be acceptable if necessary.
I ran this code with -Xmx1g and get the same exception with a different cause:
Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
    at org.apache.xmlbeans.impl.store.Cur$CurLoadContext.attr(Cur.java:3045)
    at org.apache.xmlbeans.impl.store.Cur$CurLoadContext.attr(Cur.java:3065)
    at org.apache.xmlbeans.impl.store.Locale$SaxHandler.startElement(Locale.java:3198)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:509)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:374)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2784)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:602)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:112)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:505)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:841)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:770)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:643)
    at org.apache.xmlbeans.impl.store.Locale$SaxLoader.load(Locale.java:3414)
    at org.apache.xmlbeans.impl.store.Locale.parseToXmlObject(Locale.java:1272)
    at org.apache.xmlbeans.impl.store.Locale.parseToXmlObject(Locale.java:1259)
    at org.apache.xmlbeans.impl.schema.SchemaTypeLoaderBase.parse(SchemaTypeLoaderBase.java:345)
    at org.openxmlformats.schemas.spreadsheetml.x2006.main.WorksheetDocument$Factory.parse(Unknown Source)
    at org.apache.poi.xssf.usermodel.XSSFSheet.read(XSSFSheet.java:227)
    at org.apache.poi.xssf.usermodel.XSSFSheet.onDocumentRead(XSSFSheet.java:219)
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.parseSheet(XSSFWorkbook.java:452)
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.onDocumentRead(XSSFWorkbook.java:417)
    at org.apache.poi.ooxml.POIXMLDocument.load(POIXMLDocument.java:184)
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:286)
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:323)
    at test.TestWriteOriginalWorkbook.main(TestWriteOriginalWorkbook.java:21)
Cleaning up unclosed ZipFile for archive C:\temp\Test.xlsx

To summarize the question: What can I do to improve the performance of workBook.write(fos); to handle files above 7MB size (preferably up to 15MB)?

Test.xlsx is an excel file with values only. I created it with 1 in the whole first column as well as the second column until row 443269.


text:
Q: Have a button crossing over different frames PYQT5 I have been given this image that was made in a graphic designer program and I'm trying to recreate it in Pyqt5 Python. Most of it is ok, but there are 2 buttons that overlap 2 frames, the blue arrow button at the top and the green plus button at the bottom.

Is it possible to have a button crossing over 2 frames like that? If so, how would I go about doing it without messing up the layout of everything?
Thanks for your help.


text:
Q: Encrypt Database Connection String in Azure Websites Is it possible to encrypt a database connection string and deploy it to a Windows Azure Website? (NOT a Windows Azure Web Role) If so, how?
The reason I ask is because I can't find examples or documentation anywhere as to how to perform this specifically with Azure Websites. (I'd like to use the "Shared" web site mode)
I have found the following resources, which come close to what I want, but utilize Web Roles instead of Websites:
http://archive.msdn.microsoft.com/pkcs12protectedconfg
http://blogs.msdn.com/b/windowsazure/archive/2010/09/09/securing-your-connection-string-in-windows-azure-part-3.aspx

A: The proper way to use connection strings on Azure Websites is to add "debug" connection strings to your web.config file (and by "debug" it can be a local db/storage or any string that is safe to share - empty string).
On the Azure portal go to your Azure website --> CONFIGURE tab and under connection strings sections add your actual connection strings with the same names as used in your web.config file, there the connection string are saved as encrypted strings.
The website code will get the proper connection string you set in the Azure portal.


text:
Q: Synchronous content loading Would you please help me find a way to make loading pages and elements synchronous.
I presently have:
$(Element).load(File);
... various unrelated commands...
window.onload = function ()
{
     Update_Elements(Class, Content);
}

Everything works except Update_Elements gets run prior to the load and it's changes are lost.
If I leave the load out I can see all of the updates without problems.
Where I can I use
$(Element).load(File, Update_Elements(Class, Content));

But in this situation I have conditional logic that doesn't make this possible.

A: What is this "conditional logic", and why does it make calling Update_Elements after File loads impossible?
This sequence should simply work:

*

*wait for 'load' event,

*load File & wait for it to complete,

*call Update_Elements.

window.onload = () => {
  $(Element).load(File, () => {
    Update_Elements(Class, Content);
  });
}


text:
Q: Ubuntu laptop won't turn on without external monitor I have my ubuntu mate set up with an external screen, keyboard, and mouse (total of three, plus an external harddrive occasionally) when working from home, but when we traveled recently I noticed that it was suddenly really reluctant to turn on properly without those external plugins (gave me a big fright).
It would turn on, get stuck in boot-up, and when I try to restart it, go to the safe reboot menu where it would, sometimes, successfully boot up in safe mode (and everything works once it actually manages to turn on). As soon as I got home and plugged all my usual stuff in again, everything worked as it used to.
For monitor settings, I have my laptop monitor set as the primary screen, but they both have individual menus top and bottom. I've tried unplugging everything well before turning off the system itself, but to no avail.
Does anyone have any tips on how I can make my laptop portable again?
ETA: I'm running the Ubuntu Mate 16.04. I've seen and tried to download the updates, but my laptop has no ethernet port and the download always fails because the wifi is too slow.


text:
Q: React Router 6 and Typescript - index attribute Type 'true' is not assignable to type 'false | undefined'.? I'm trying to create an index route for one of my child routes in it's parent route but I keep on getting and error which says Type 'true' is not assignable to type 'false | undefined'. How do I fix it?
<Routes>
  <Route path="/" element={<Profile />}>
    <Route index path="/username" element={<ProfileDetails />} />
    <Route path="settings/profile" element={<EditProfile />} />
  </Route>
  <Route path="/login" element={<Login />} />
  <Route path="/register" element={<SignUp />} />
</Routes>

A: Fixed it. It was because of the path
<Routes>
  <Route path="/" element={<Profile />}>
    <Route index element={<ProfileDetails />} />
    <Route path="/username" element={<ProfileDetails />} />
    <Route path="settings/profile" element={<EditProfile />} />
  </Route>
  <Route path="/login" element={<Login />} />
  <Route path="/register" element={<SignUp />} />
</Routes>

A:
You don't need a path when index is true because whenever there is a profile page you will see your profile details. Purpose of index is to use when we want the path of parent to used.

<Routes>
  <Route path="/" element={<Profile />}>
    <Route index element={<ProfileDetails />} />
    <Route path="settings/profile" element={<EditProfile />} />
  </Route>
  <Route path="/login" element={<Login />} />
  <Route path="/register" element={<SignUp />} />
</Routes>


text:
Q: User has db_owner through AD group but cannot create table We've setup a SQL Server 2012 Enterprise, and through certain domain user groups, users are granted access to several databases.
For instance, group 'ADB' has for several databases following rights:
Server role: public
User mapping: db_datareader, db_writer, db_owner, db_public
Now, our application sometimes needs to execute certain queries. One of them was a CREATE TABLE statement. When a user of the group 'ADB' opens the application of us, in the background the script is run to CREATE TABLE. But it doesn't do that, because the user has no right to create. I don't understand because that user is part of a domain group that is DB_OWNER.
If I run a T-SQL command that shows all the members of db_owner, I don't see the AD group 'ADB' (as I would have expected) for those databases, but I do see 'sa'. Could this be the cause of my problem?
Hundreds of databases have rights assigned through server roles and user mapping, manually through SSMS. So it will be a lot of work fixing those things, but maybe it can be done through scripting. All I want to know is, why a user can't do a create table if he is part of a domain group that is db_owner of a database?

A: There are so many possibilities, but here are a few things to check:

*

*that the user is a member of the ADB group in the Active Directory.

*that ADB exists as a server principal (a login). Example: SELECT * FROM sys.server_principals WHERE [name] LIKE '%ADB';

*that this login has a user in the database in question: SELECT * FROM myDatabaseName.sys.database_principals WHERE [sid] IN (SELECT [sid] FROM sys.server_principals WHERE [name] LIKE '%ADB');

*that the database principal (the user) is a member of db_owner (not to be confused with schema ownership)

*like @mlachman points out in another answer, that the database principal hasn't been specifically denied any actions.

Also,

*

*You don't need db_public, db_datareader or db_datawriter on ADB, if it's db_owner. Good housekeeping to clean those memberships up, and it may even help with your problem.

If it's any use to you, I've written a script that compiles all of the permissions in a database. It's available on the Downloads page of my blog, and it's completely "as-is", without any warranty or guarantee.

A: Please check in [Database Properties-> Permissions Tab] and check if there are any denies on Create Table option. Also on the other roles like db_public .


text:
Q: Restarting Springboot Application via batch script I have a Springboot application which I need to restart upon returning some exit code(System.exit(5)) say. I know nothing about writing batch script.
Upon searching I found code which seems for a Java core Application.
@echo off

:start

java SpringBootApp %1
set exitcode=%ERRORLEVEL%
pause
if %exitcode% == "5" (goto :start)

Other methods were of using jar files, but I would like to avoid it if possible.
Please help!


text:
Q: Sort column B while keeping column A's order In Excel, I have 2 columns. I want to sort the second one in alphabetical order while keeping the (custom) order in the first one (think std::stable_sort where equality is  based on the first column only). Example:
dsf   k
www   d
www   a
azd   q
azd   e
azd   b

should become
dsf   k
www   a
www   d
azd   b
azd   e
azd   q

The sorting wizard doesn't seem to have any "keep current order" option. I could define the custom order but I have more than a thousand different elements; that would be a real pain to do and this custom order can change at any time.

A: I'll assume that your data start in Row 2, and that Column C is available for use as a "helper column".  Put
=IF(A1=A2, C1, C1+1)

into cell C2.  (If Column C isn't available, use one that is.
If your data start in Row 1, either insert a blank row,
or (still) put the above into cell C2, but put 1 into cell C1.)
Drag/fill down.
This (Column C) now "documents" your custom order;
e.g., C2 = 1,C3 = C4 = 2, andC5 = C6 = C7 = 3.
Now sort on Column C and Column B.

A: I think your best bet is to use custom orders.  If it doesn't have to be updated to often you could do it through FILE>OPTIONS>ADVANCED>EDIT CUSTOM LISTS... and just import the entire range.  Then use that when sorting.
VBA solution would be something like

Sub sort()
Dim iCustListNum As Integer

iCustListNum = Application.CustomListCount + 1
Application.AddCustomList ListArray:=Range("A2:A100")

On Error GoTo err:

'Sort your list
Range("A1:B100").sort Key1:=Range("A1"), Order1:=xlAscending, OrderCustom:=iCustListNum, _
    Key2:=Range("B1"), Order2:=xlAscending, Header:=xlYes, _
    MatchCase:=False, Orientation:=xlTopToBottom

'Clean up
err:
Application.DeleteCustomList ListNum:=iCustListNum

End Sub

A: Quick and dirty:-

*

*Copy the contents of column A into notepad, then recopy to the clipboard.

*Select both columns.

*Select the sort function and sort column A using the "custom list" order.

*Enter the data from the clipboard into the custom list.

*Add a level to the sort function and then sort by column B, "smallest to largest".


text:
Q: Example of non-reversible folding of a thin chamber complex. In Abramenko-Brown's book "Building Theory and Applications" section 3.4.1 page 129, the authors define the 'opposite' of a folding of a thin chamber complex. They mention that the opposite is defined only on the chambers and therefore it is not necessarily a folding itself (i.e. a simplicial map). A folding is called reversible if its opposite is indeed a folding. In Garrett's book the same subtlety appears.
Question : I am looking for an example of a non reversible folding of a thin chamber complex. The example should not be a Coxeter complex where the foldings are always reversible, I believe.

A: Start with a regular triangulation of the plane, say the one by equilateral triangles. Note that this is a thin chamber complex. Moreover, you can reflect through any of the lines in the triangulation. Now take two vertices which are of distance at least three apart and glue them together. The result is still a thin chamber complex. (I needed the vertices to be sufficiently far apart for the result to still be a simplicial complex.) Now fix a line which has both identified vertices to the same side of it (call this half-space with two points identified $\Phi$). Then one can fold across the line in one direction, toward $\Phi$, by first identifying two vertices on one side and then folding. You can't fold in the other direction because the fold was not a bijection on vertices. (To go the other way, you'd have to disidentify two vertices, which is not even  going to give you a function.) This fold works fine on chambers and does everything you want it to on codimension 1 faces. It messes up at codimension 2.


text:
Q: Quadratic/ Cubic/ etc approximations without the Taylor series It's easy to convince someone that the linear approximation is the best line which approximates a function at a point because everyone learns early that the derivative of a function is just the slope of that function at the point.
However...
Assuming I'd never heard of Taylor series, is there some way you could convince me that $f(a)-f'(a)(x-a) - \frac 12f''(a)(x-a)^2$ is the best quadratic function that describes the function $f$ at the point $x=a$?
Bonus points: How about the best cubic or quartic or quintic or .... approximation?

A: Write $f(x)\approx a_0+a_1(x-a)+a_1(x-a)^2$.  Then, determine coefficients by taking successive derivatives and letting $x=a$.
So, $f(a)=a_0$. $f'(a)=a_1$.  $f''(a)=2a_2$.
The same procedure can be used for any order of "approximation."  However, this does not establish the validity of the process.  Nor does it provide any estimate of the size of the error.  It only gives a heuristic way of looking at the elegant development that is Taylor's expansion.

A: Well, to be awkward and annoying, you can define the derivative as the number $f'(a)$ so that
$$ \frac{f(a+h)-f(a)-h f'(a)}{h} \to 0 $$
as $h \to 0$, i.e. so that
$$ f(a+h) = f(a) + h f'(a) + o(h). $$
In a similar way, you can define the second derivative as the number $f''(a)$ such that
$$ \frac{f(a+h)-f(a)-h f'(a)-h^2 f''(a)/2 }{h^2} \to 0,  $$
and so on. That there is only one such number $f^{(k)}(a)$ for each $k$ up to $n$ is exactly what it means for a function to be $n$-times differentiable.


text:
Q: Which types of errors should stop the system, in released php web system? While developing a php web system, setting E_ALL | E_STRICT to error_reporting and taking care of all kind of errors including notice errors is good practice.
But in the released system, should I stop the system when notice error occurred?
Or should I stop the system only when E_ERROR occurred and ignore all other errors such as E_WARNING, E_NOTICE, or E_STRICT?
Which types of errors should I handle in my custom error handler and stop(exit) the system?

A: When you develop a code you should take care of any warning including notices.
For production your should not really halt on errors. Instead you can use set_error_handler() to manage any errors such as E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE. Redirect client to custom page, display a custom message for any type of error. The point is not to leave the default error information.
You should always have a system that reports any errors encountered to yourself (via e-mail or such) on production servers and take care of them as soon as possible.
On php.net/set_error_handler you have plenty of examples that will make your life a lot easier and help you track errors and warnings.


text:
Q: Multiple definitions of inline function C++ I know there is already a lot of topics about this subject, however I didn't find in any of them the explanation to how it is possible to have one definition of an inline function per translation unit. I know that inline functions have external linkage, so when I call one inline function in different translation units they all reference the same function. I also know that in Linux the compiler registers inline function with the "W" symbol, so it is registered as a weak symbol (thanks to it the first definition encountered by the compiler of the inline function is the one considered). However whenever I use nm on the object files created by g++ in Windows there is no weak symbol attached to the function signature. How can the linker know which definition to consider and not to accuse of multiple definitions? (I don't show the linker's work but I tested it).
Here is some example code:
// main1.cpp
#include "main.hpp"

/* inline accepts one definition in each TU's */

inline void Test::hello_world()
{
    std::cout << "Hello world" << std::endl;
}

/*void Test::hello_world()
{
    std::cout << "Hello world" << std::endl;
}*/

extern void return_hello_world();

int main()
{
    Test t;
    t.hello_world();
    return_hello_world();
    return 0;
}

// main2.cpp
#include "main.hpp"

/* inline accepts one definition in each TU's */

inline void Test::hello_world()
{
    std::cout << "Hello world" << std::endl;
}

/* void Test::hello_world()
{
    std::cout << "Hello world" << std::endl;
} */

void return_hello_world()
{
    Test t;
    t.hello_world();
}

// main.hpp
#ifndef TEST
#define TEST
#include <iostream>

class Test
{
public:
    void hello_world();
};

#endif

The results I receive are:

*

*Windows:

    Experimentation4> g++ -g -O0 -c main1.cpp main2.cpp
    Experimentation4> nm main1.o
    0000000000000000 b .bss
    0000000000000000 d .ctors
    0000000000000000 d .data
    0000000000000000 N .debug_abbrev
    0000000000000000 N .debug_aranges
    0000000000000000 N .debug_frame
    0000000000000000 N .debug_info
    0000000000000000 N .debug_line
    0000000000000000 N .debug_ranges
    0000000000000000 N .debug_str
    0000000000000000 p .pdata
    0000000000000000 p .pdata$_ZN4Test11hello_worldEv
    0000000000000000 r .rdata
    0000000000000000 r .rdata$.refptr._ZSt4cout
    0000000000000000 r .rdata$.refptr._ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_
    0000000000000000 r .rdata$zzz
    0000000000000000 R .refptr._ZSt4cout
    0000000000000000 R .refptr._ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_
    0000000000000000 t .text
    0000000000000000 t .text$_ZN4Test11hello_worldEv
    0000000000000000 r .xdata
    0000000000000000 r .xdata$_ZN4Test11hello_worldEv
                     U __main
    0000000000000029 t __tcf_0
    0000000000000080 t _GLOBAL__sub_I_main
                     U _Z18return_hello_worldv
    0000000000000044 t _Z41__static_initialization_and_destruction_0ii
    0000000000000000 T _ZN4Test11hello_worldEv
                     U _ZNSolsEPFRSoS_E
                     U _ZNSt8ios_base4InitC1Ev
                     U _ZNSt8ios_base4InitD1Ev
                     U _ZSt4cout
                     U _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_
    0000000000000000 r _ZStL19piecewise_construct
    0000000000000000 b _ZStL8__ioinit
                     U _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc
                     U atexit
    0000000000000000 T main

*

*Linux:

    Experimentation2$ g++ -O0 -g -c main1.cpp main2.cpp
    Experimentation2$ nm main1.o
                     U __cxa_atexit
                     U __dso_handle
    0000000000000081 t _GLOBAL__sub_I_main
    0000000000000000 T main
                     U __stack_chk_fail
                     U _Z18return_hello_worldv
    0000000000000043 t _Z41__static_initialization_and_destruction_0ii
    0000000000000000 W _ZN4Test11hello_worldEv
                     U _ZNSolsEPFRSoS_E
                     U _ZNSt8ios_base4InitC1Ev
                     U _ZNSt8ios_base4InitD1Ev
                     U _ZSt4cout
                     U _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_
    0000000000000000 b _ZStL8__ioinit
                     U _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc


text:
Q: How to choose the parameters of a bilateral filter? I am using bilateral filter from OpenCV. Can you please tell me if there is a correlation with the image extension? I mean something like this:
if 500 < image.shape[1] < 1000 and 500 < image.shape[0] < 1000:
    result = cv2.bilateralFilter(image, ?, ?, ?)

I'm pursuing the goal of dynamically automatically selecting parameters depending on the image.


text:
Q: Independence of a line integral from the path I'd like to understand why this statement is true:
If $C$ is a simple closed smooth curve in the plane $x+y+z=1$, then $$\int_C zdx-2xdy+3ydz$$ depends only on the orientation of $C$ and the area of the region enclosed by $C$ but not on the shape of $C$ or its location in the plane.
What is a criterion I can use to verify this? Am I supposed to apply Stokes' theorem? If so, how exactly?

A: We have

*

*$\vec F=(z,-2x,3y) \implies \nabla \times \vec F=3i+j-2k$

and
$$(\nabla \times \vec F)\cdot d\vec S=(3i+j-2k)\cdot\frac1{\sqrt3}(i+j+k) \,dS=\frac2{\sqrt3}\,dS$$

A: Yes, you use Stoke's Theorem.  With Stoke's, this integral becomes
$$\int_S <3,1,-2> \cdot dS$$
And as long as the curve is in the plane the integral reduces to 2 times the enclosed area.


text:
Q: How can I use gzip on a string? I want to use Go to read out a chunk from a file, treat it as a string and gzip this chunk. I know how to read from the file and treat it as a string, but when it comes to compress/gzip I am lost.
Should I create an io.writer, which writes to a buf (byte slice), use gzip.NewWriter(io.writer) to get a w *gzip.Writer and then use w.Write(chunk_of_file) to write the chunk of file to buf? Then I would need to treat the string as a byte slice.

A: You can just write using gzip.Writer as it implements io.Writer.
Example:
package main

import (
    "bytes"
    "compress/gzip"
    "fmt"
    "log"
)

func main() {
    var b bytes.Buffer
    gz := gzip.NewWriter(&b)
    if _, err := gz.Write([]byte("YourDataHere")); err != nil {
        log.Fatal(err)
    }
    if err := gz.Close(); err != nil {
        log.Fatal(err)
    }
    fmt.Println(b.Bytes())
}

Go Playground
If you want to set the compression level (Default is -1 from compress/flate) you can use gzip.NewWriterLevel.

A: If the result is not going back into a file, then you could just use Flate
directly. You save a bit of overhead from Gzip. Another option is Brotli.
Examples:
package main

import (
   "bytes"
   "compress/flate"
   "github.com/andybalholm/brotli"
)

func compressFlate(data []byte) ([]byte, error) {
   var b bytes.Buffer
   w, err := flate.NewWriter(&b, 9)
   if err != nil {
      return nil, err
   }
   w.Write(data)
   w.Close()
   return b.Bytes(), nil
}

func compressBrotli(data []byte) []byte {
   var b bytes.Buffer
   w := brotli.NewWriterLevel(&b, brotli.BestCompression)
   w.Write(data)
   w.Close()
   return b.Bytes()
}

Result:
package main

import (
   "bytes"
   "fmt"
)

func main() {
   data := bytes.Repeat([]byte("hello world"), 999_999)
   f, err := compressFlate(data)
   if err != nil {
      panic(err)
   }
   b := compressBrotli(data)
   fmt.Println(len(f) == 21379, len(b) == 40)
}

*

*https://godocs.io/compress/flate

*https://godocs.io/github.com/andybalholm/brotli


text:
Q: Why is Array.fill() not available whit ES6 target I'm migrating some js code to typescript and I'm facing some issues with Array.fill.
I used to have this code
Array(4).fill(0).map()

and I changed it to
Array<number>(4).fill(0).map()

but I get this error
Error:(22, 49) TS2339:Property 'fill' does not exist on type 'number[]'.

My tsconfig.json looks like
{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "removeComments": false,
    "outDir": "dist",
    "allowJs": true
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.js"
  ],
  "exclude": [
    "node_modules",
    "dist",
    "src/**/*.spec.ts",
    "src/**/*.spec.js"
  ]
}

I already check this issue #9436.
Did I miss something ?

A: try this :
let arr:Array<Number>=new Array(8);
arr.fill(0);

hope it helps :)


text:
Q: Failure to display DataTable in RShiny App I'm hoping to display a reactive datatable for my Shiny app. I'm using renderDataTable() and have made sure that the data table is returned in the reactive function. I've noticed that the datatable renders fine outside of the Shiny App, so not a variable/computation error. The reason I'm hoping to use a datatable in the first place is so that I can display cleaned up column names and display the dataframe in a more clean manner. Please let me know what else I can try, or if I should change my approach.
Here is the server code:
server <- function(input, output) {

  dataset <- reactive({
    shiny_tuition_salary <- datatable(df_tuition_salary %>%
                                        select(name, mean_net_cost, state) %>%
                                        filter(mean_net_cost >= input$input_budget[1],
                                               mean_net_cost <= input$input_budget[2],
                                               state == input$input_state) %>%
                                        select(name, mean_net_cost))

    return(shiny_tuition_salary)
  })

  output$df <- renderDataTable({

    dataset()

  })

}

Currently nothing is displayed under the Table tab in the app. The app also successfully displays the table when DataTable is not used at all (i.e. removing datatable() from the server and using RenderTable instead of RenderDataTable), so I'm positive there's an issue with my implementation of RenderDataTable()
Thanks!
EDIT: Here's the ui code and a sample df_tuition_salary as well
ui <- fluidPage(

  titlePanel("What colleges match your budget and rank?"),

  # Sidebar laayout with input and output definitions ----
  sidebarLayout(

    # Sidebar panel for inputs ----
    sidebarPanel(

      # Input: Slider for the number of bins ----
      sliderInput(inputId = "input_budget",
                  label = "Budget:",
                  min = 0,
                  max = 50000,
                  value = c(0, 15000)),
      selectInput(inputId = "input_state",
                  label = "State (limited data, may limit options):",
                  choices = df_tuition_salary$state)

    ),

    # Main panel for displaying outputs ----
    mainPanel(
      tabsetPanel(
        id = 'output_df',
        # tabPanel("Plot", plotOutput("plot")),
        tabPanel("Table", tableOutput("df"))
      )

    )
  )
)

df_tuition_salary:
df_tuition_salary <- data.frame(name = c("Aaniiih Nakoda College", "Abilene Christian University"),
           mean_net_cost = c(7508.2414, 24884.0828),
           state = c("N/A", "N/A"))

A: use dataTableOutput() function.
# Main panel for displaying outputs ----
    mainPanel(
      tabsetPanel(
        id = 'output_df',
        # tabPanel("Plot", plotOutput("plot")),
        tabPanel("Table", dataTableOutput("df"))
      )


text:
Q: How to crop a UIImageView to a new UIImage in 'aspect fit' mode?
I would like to create a new UIImage by cropping the image inside a UIImageView.  For example in the above pic, I want a new UIImage of the area outlined in green.  I found code to do this, normally it looks something like this (as a UIImage category):
- (UIImage *)croppedImage:(CGRect)bounds {
    CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], bounds);
    UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    return croppedImage;
}

Makes perfect sense.  HOWEVER, my UIImageView is in contentMode 'aspect fit'.  Seems like that complicates the CGRect calculations for CGImageCreateWithImageInRect and I haven't been able to figure out the right solution.
I figure I need to apply the same transformations to the green rect as were done to the image?
ALSO:  I found this other question here (How to know the image size after applying aspect fit for the image in an UIImageView), which seems to show a brute force way of getting the size, but I am still not sure how that fits into a cropping situation.
Any ideas?
EDIT: In my case, I literally have a square as shown above drawn in an overlay view over the UIImageView.   So while I realize I am cropping the UIImage (inside the UIImageView), I need to somehow change the green CGRect such that it 'matches' the transformation done when 'aspect fit' is applied.   For example, if I leave my UIImageView in 'top left' mode, then everything works fine, because there is a 1:1 mapping between the underlying UIImage and the UIImageView.  The problem in 'top left' mode is that the entire image doesn't always display, because it might be bigger than my UIImageView.

A: I know the answer has been but I had some problems getting above right so, I wont to post my solution too.
The problem is the image is scaled with a aspect fit, but we know the scale factor for both the width and the height. Then we can calculate the right cropping rectangle pretty easy:
-(UIImage*)crop:(CGRect)frame
{
    // Find the scalefactors  UIImageView's widht and height / UIImage width and height
    CGFloat widthScale = self.bounds.size.width / self.image.size.width;
    CGFloat heightScale = self.bounds.size.height / self.image.size.height;

    // Calculate the right crop rectangle
    frame.origin.x = frame.origin.x * (1 / widthScale);
    frame.origin.y = frame.origin.y * (1 / heightScale);
    frame.size.width = frame.size.width * (1 / widthScale);
    frame.size.height = frame.size.height * (1 / heightScale);

    // Create a new UIImage
    CGImageRef imageRef = CGImageCreateWithImageInRect(self.image.CGImage, frame);
    UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);

    return croppedImage;
}

A: Based on my other answer to a similar question I have written this method for a UIImageView category:
-(CGRect) cropRectForFrame:(CGRect)frame
{
    NSAssert(self.contentMode == UIViewContentModeScaleAspectFit, @"content mode must be aspect fit");

    CGFloat widthScale = self.bounds.size.width / self.image.size.width;
    CGFloat heightScale = self.bounds.size.height / self.image.size.height;

    float x, y, w, h, offset;
    if (widthScale<heightScale) {
        offset = (self.bounds.size.height - (self.image.size.height*widthScale))/2;
        x = frame.origin.x / widthScale;
        y = (frame.origin.y-offset) / widthScale;
        w = frame.size.width / widthScale;
        h = frame.size.height / widthScale;
    } else {
        offset = (self.bounds.size.width - (self.image.size.width*heightScale))/2;
        x = (frame.origin.x-offset) / heightScale;
        y = frame.origin.y / heightScale;
        w = frame.size.width / heightScale;
        h = frame.size.height / heightScale;
    }
    return CGRectMake(x, y, w, h);
}

You can pass in the frame of your green rect (assuming it is a subview of the image view) and get the crop rect back for cropping the UIImage. Note that it only works for 'aspect fit' mode! I haven't tested it though. So, tell me if it works!

A: I think you don't understand what you are doing. You can't "crop" a UIImageView - only UIImages. So your croppedImage method should be in a UIImage category and not a UIImageView category.
The bounds rect you pass to the crop method must be in relation to the image size, not to the imageview bounds.
It is irrelevant what the contentMode of the image view is - the cropping of the image will always work the same. First get the image from the image view. Then create a new cropped image from it and finally set the cropped image for the image view. This can be done in one line of code:
imageView.image = [imageView.image croppedImage:rect];

Since your contentMode is 'aspect fit' the new image will automatically stretch to fit in the view frame. You can also try to change the view frame based on the image.size to avoid pixelation effects.

A: I use the method below.
-(UIImage *)getNeedImageFrom:(UIImage*)image cropRect:(CGRect)rect
{
   CGSize cropSize = rect.size;
   CGFloat widthScale =
   image.size.width/self.imageViewOriginal.bounds.size.width;
   CGFloat heightScale =
   image.size.height/self.imageViewOriginal.bounds.size.height;
   cropSize = CGSizeMake(rect.size.width*widthScale,
   rect.size.height*heightScale);
   CGPoint  pointCrop = CGPointMake(rect.origin.x*widthScale,
   rect.origin.y*heightScale);
   rect = CGRectMake(pointCrop.x, pointCrop.y, cropSize.width,
   cropSize.height);
   CGImageRef subImage = CGImageCreateWithImageInRect(image.CGImage, rect);
   UIImage *croppedImage = [UIImage imageWithCGImage:subImage];
   CGImageRelease(subImage);
   return croppedImage;

   }


text:
Q: How to use gestures with scrollview - Android? I am using onFling in my views to get a swipe to next activity. However this does not work if the view has a scrollview surrounding it.
Apparently it absorbs the gestures and stops my onFling.
Is there anyway around this issue?

A: You are right, ScrollView "steals" the gesture because of it's inherit functionality. I've worked around this before by applying the onTouchListener to the ScrollView itself instead of its immediate parent view.

A: Check this piece of code: (Override ScrollView's dispatchTouchEvent)
public class yourScrollView extends ScrollView{

    //constructors and everything
    //You might want to pass your GestureDetector (of course)

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev){
        super.dispatchTouchEvent(ev);
        return myGestureDetector.onTouchEvent(ev);
    }
}

A: I can't comment answers so I write a new one.
I found that overriding the dispatchTouchEvent of ScrollView works well but the gesture handler needs to be called before the super.dispatchTouchEvent as that method could change the event coordinates in some weird way. In particular I have seen the Y value jumping when trying to vertically scroll past the end of the view.
Calling the gesture handler before the scroll view handling will let it use the scroll view coordinates and not the internal scrolled ones.
So:
public class yourScrollView extends ScrollView{

    //constructors and everything

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev){
        return myGestureDetector.onTouchEvent(ev) | super.dispatchTouchEvent(ev);
    }
}

Elements in the scroll view react as long as the view does not start scrolling, but the gestures are correctly detected.


text:
Q: Group by "Removed" status on Azure devops dashboard I have a requirement to create a dashboard using VSTS (azure devops) that gets me the trend of bugs that are removed (rejected). I tried to use the "Chart", Group By "State" and "Last Year" for the rolling period in the dashboard. It works fine for New, Approved and Committed. But it doesn't work for the Done and Removed. For Done and removed it returns the cumulative count. For e.g if 3 bugs are removed in Jan, 4 bugs removed in Feb and 3 bugs in March, it returns 3 for Jan, 7 for Feb and 10 for Mar in the chart. Is there anyway to get the actual counts instead of the cumulative counts. Please help.

A: If you want the actual counts about the Done and Removed State, you can change your chart type to others, such like pie.

Then you will get the result as below.

The testquery1 is used to query all bugs.


text:
Q: Useful little functions in R? What are the functions that you wrote, don't quite deserve a package, but you wish to share?
I will throw in some of mine:
destring <- function(x) {
    ## convert factor to strings
    if (is.character(x)) {
        as.numeric(x)
    } else if (is.factor(x)) {
        as.numeric(levels(x))[x]
    } else if (is.numeric(x)) {
        x
    } else {
        stop("could not convert to numeric")
    }
}

pad0 <- function(x,mx=NULL,fill=0) {
  ## pad numeric vars to strings of specified size
  lx <- nchar(as.character(x))
  mx.calc <- max(lx,na.rm=TRUE)
  if (!is.null(mx)) {
    if (mx<mx.calc) {
      stop("number of maxchar is too small")
    }
  } else {
    mx <- mx.calc
  }
  px <- mx-lx
  paste(sapply(px,function(x) paste(rep(fill,x),collapse="")),x,sep="")
}

.eval <- function(evaltext,envir=sys.frame()) {
  ## evaluate a string as R code
  eval(parse(text=evaltext), envir=envir)
}

## trim white space/tabs
## this is marek's version
trim<-function(s) gsub("^[[:space:]]+|[[:space:]]+$","",s)

A: # Create a circle with n number of "sides" (kudos to Barry Rowlingson, r-sig-geo).
circle <-  function(x = 0, y = 0, r = 100, n = 30){
    t <- seq(from = 0, to = 2 * pi, length = n + 1)[-1]
    t <- cbind(x = x + r * sin(t), y = y + r * cos(t))
    t <- rbind(t, t[1,])
    return(t)
}
# To run it, use
plot(circle(x = 0, y = 0, r = 50, n = 100), type = "l")

A: It was annoying to me how data.frame with many columns is printed, I mean this split over columns. So I wrote my own version:
print.data.frame <- function(x, ...) {
    oWidth <- getOption("width")
    oMaxPrint <- getOption("max.print")
    on.exit(options(width=oWidth, max.print=oMaxPrint))
    options(width=10000, max.print=300)
    base::print.data.frame(x, ...)
}

A: I frequently want to use sum contrasts in regressions, and I usually want the terms to be meaningfully named. So I wrote this recontrast function.
recontrast<-function(data,type = "sum"){
    data.type <-class(data)
    if(data.type == "factor"&!is.ordered(data)&nlevels(data)>1&nlevels(data)<1000){
        if(type == "sum"){
            contrasts(data)<-contr.sum(levels(data))
            colnames(contrasts(data))<-levels(data)[-nlevels(data)]
        }else if(type == "treatment"){
            contrasts(data)<-contr.treatment(levels(data))
        }
    }else if(data.type == "data.frame"){
        for(i in 1:ncol(data)){
            if(is.factor(data[,i]) &     !is.ordered(data[,i])&nlevels(data[,i])>1&nlevels(data[,i])<1000){
                if(type == "sum"){
                    contrasts(data[,i])<-contr.sum(levels(data[,i]))
                    colnames(contrasts(data[,i]))<-levels(data[,i])[-    nlevels(data[,i])]
                }else if(type == "treatment"){
                    contrasts(data[,i])<-    contr.treatment(levels(data[,i]))
                }
            }
        }
    }
return(data)
}

It take both entire dataframes and factors as arguments. If it's a data frame, it'll convert  all contrasts of unordered factors with <1000 levels to either treatment or sum contrasts. With sum contrasts, it meaningfully names the columns, so you'll have meaningful labels in the regression output.

A: Here's a little function to plot overlapping histograms with pseudo-transparency:

(source: chrisamiller.com)
plotOverlappingHist <- function(a, b, colors=c("white","gray20","gray50"),
                            breaks=NULL, xlim=NULL, ylim=NULL){

  ahist=NULL
  bhist=NULL

  if(!(is.null(breaks))){
    ahist=hist(a,breaks=breaks,plot=F)
    bhist=hist(b,breaks=breaks,plot=F)
  } else {
    ahist=hist(a,plot=F)
    bhist=hist(b,plot=F)

    dist = ahist$breaks[2]-ahist$breaks[1]
    breaks = seq(min(ahist$breaks,bhist$breaks),max(ahist$breaks,bhist$breaks),dist)

    ahist=hist(a,breaks=breaks,plot=F)
    bhist=hist(b,breaks=breaks,plot=F)
  }

  if(is.null(xlim)){
    xlim = c(min(ahist$breaks,bhist$breaks),max(ahist$breaks,bhist$breaks))
  }

  if(is.null(ylim)){
    ylim = c(0,max(ahist$counts,bhist$counts))
  }

  overlap = ahist
  for(i in 1:length(overlap$counts)){
    if(ahist$counts[i] > 0 & bhist$counts[i] > 0){
      overlap$counts[i] = min(ahist$counts[i],bhist$counts[i])
    } else {
      overlap$counts[i] = 0
    }
  }

  plot(ahist, xlim=xlim, ylim=ylim, col=colors[1])
  plot(bhist, xlim=xlim, ylim=ylim, col=colors[2], add=T)
  plot(overlap, xlim=xlim, ylim=ylim, col=colors[3], add=T)
}

An example of how to run it:
a = rnorm(10000,5)
b = rnorm(10000,3)
plotOverlappingHist(a,b)

Update: FWIW, there's a potentially simpler way to do this with transparency that I've since learned:
a=rnorm(1000, 3, 1)
b=rnorm(1000, 6, 1)
hist(a, xlim=c(0,10), col="red")
hist(b, add=T, col=rgb(0, 1, 0, 0.5)

A: The output of the fft (Fast Fourier Transform) function in R can be a little bit tedious to process. I wrote this plotFFT function in order to do a frequency vs power plot of the FFT. The getFFTFreqs function (used internally by plotFFT) returns the frequency associated to each FFT value.
This was mostly based on the very interesting discussion at http://tolstoy.newcastle.edu.au/R/help/05/08/11236.html
# Gets the frequencies returned by the FFT function
getFFTFreqs <- function(Nyq.Freq, data)
    {
    if ((length(data) %% 2) == 1) # Odd number of samples
        {
        FFTFreqs <- c(seq(0, Nyq.Freq, length.out=(length(data)+1)/2),
               seq(-Nyq.Freq, 0, length.out=(length(data)-1)/2))
        }
    else # Even number
        {
        FFTFreqs <- c(seq(0, Nyq.Freq, length.out=length(data)/2),
               seq(-Nyq.Freq, 0, length.out=length(data)/2))
        }

    return (FFTFreqs)
    }

# FFT plot
# Params:
# x,y -> the data for which we want to plot the FFT
# samplingFreq -> the sampling frequency
# shadeNyq -> if true the region in [0;Nyquist frequency] will be shaded
# showPeriod -> if true the period will be shown on the top
# Returns a list with:
# freq -> the frequencies
# FFT -> the FFT values
# modFFT -> the modulus of the FFT
plotFFT <- function(x, y, samplingFreq, shadeNyq=TRUE, showPeriod = TRUE)
    {
    Nyq.Freq <- samplingFreq/2
    FFTFreqs <- getFFTFreqs(Nyq.Freq, y)

    FFT <- fft(y)
    modFFT <- Mod(FFT)
    FFTdata <- cbind(FFTFreqs, modFFT)
    plot(FFTdata[1:nrow(FFTdata)/2,], t="l", pch=20, lwd=2, cex=0.8, main="",
        xlab="Frequency (Hz)", ylab="Power")
    if (showPeriod == TRUE)
        {
        # Period axis on top
        a <- axis(3, lty=0, labels=FALSE)
        axis(3, cex.axis=0.6, labels=format(1/a, digits=2), at=a)
        }
    if (shadeNyq == TRUE)
        {
        # Gray out lower frequencies
        rect(0, 0, 2/max(x), max(FFTdata[,2])*2, col="gray", density=30)
        }

    ret <- list("freq"=FFTFreqs, "FFT"=FFT, "modFFT"=modFFT)
    return (ret)
    }

As an example you can try this
# A sum of 3 sine waves + noise
x <- seq(0, 8*pi, 0.01)
sine <- sin(2*pi*5*x) + 0.5 * sin(2*pi*12*x) + 0.1*sin(2*pi*20*x) + 1.5*runif(length(x))
par(mfrow=c(2,1))
plot(x, sine, "l")
res <- plotFFT(x, sine, 100)

or
linearChirp <- function(fr=0.01, k=0.01, len=100, samplingFreq=100)
    {
    x <- seq(0, len, 1/samplingFreq)
    chirp <- sin(2*pi*(fr+k/2*x)*x)

    ret <- list("x"=x, "y"=chirp)
    return(ret)
    }

chirp <- linearChirp(1, .02, 100, 500)
par(mfrow=c(2,1))
plot(chirp, t="l")
res <- plotFFT(chirp$x, chirp$y, 500, xlim=c(0, 4))

Which give

(source: nicolaromano.net)

(source: nicolaromano.net)

A: Very simple but i use it a lot:
setdiff2 <- function(x,y) {
    #returns a list of the elements of x that are not in y
     #and the elements of y that are not in x (not the same thing...)

    Xdiff = setdiff(x,y)
    Ydiff = setdiff(y,x)
    list(X_not_in_Y=Xdiff, Y_not_in_X=Ydiff)
}

A: In the most useful R trick posting I saw a post by Keving from Nov 3 '09 bout dropping unused levels. The first function was provided there. and I took the best step in the second function to drop levels from a subset.
drop.levels <- function (dat) {if (is.factor(dat)) dat <- dat[, drop = TRUE] else dat[] <- lapply(dat, function(x) x[, drop = TRUE]); return(dat) ;};

subset.d    <- function (...) drop.levels(subset(...)); # function to drop levels of subset


text:
Q: get row data from Nx's tensor variable response error message enter link description here
The sample code give the error message as follows:
iex(37)> tensor =
...(37)>   1..4
1..4
iex(38)>   |> Enum.chunk_every(2)
[[1, 2], [3, 4]]
iex(39)>   |> Nx.tensor(names: [:y, :x])
#Nx.Tensor<
  s64[y: 2][x: 2]
  [
    [1, 2],
    [3, 4]
  ]
>

iex(33)> tensor[x: 1]
** (UndefinedFunctionError) function Range.fetch/2 is undefined (Range does not implement the Access behaviour)
    (elixir 1.13.4) Range.fetch(1..4, [x: 1])
    (elixir 1.13.4) lib/access.ex:285: Access.get/3
iex(33)> tensor[y: 0..1]
** (UndefinedFunctionError) function Range.fetch/2 is undefined (Range does not implement the Access behaviour)
    (elixir 1.13.4) Range.fetch(1..4, [y: 0..1])
    (elixir 1.13.4) lib/access.ex:285: Access.get/3


text:
Q: How do you write a 3d game? I have always wondered, how do game programmers tie together game characters done in an external 3d modeling software like maya or 3d max and the actual game logic done in there favourite programming language e.g c or c++.
How do you get to combine this two things together, and what is the actual process of building a game from modeling characters to programming?
Some of the things that make me wonder are like, do you program characters movements from the code or from the 3d model?
Examples would be really nice to see.

A: Unlike the favorite answer, I would venture and say that this is actually quite a big task if you refer to having a character that have animaton to it.
The end result would be to enable most of functionality tied via script and config files (in other words - data driven), but the process to build such a system is not simple.
Usually you start with an external modeler where you do the following:
1. construct a skin model.
2. construct a skeleton and attach to the skin according to weights etc..
3. apply all textures and material as desired.
4. export to your engine.
Now you can start build your animation bank for this character skeleton or any similar one if you associate it to more than one (usually that's the case if the skeleton is close enough or modular).
Some of the animations will contain only partial hierarchy (to be able to blend only part of the animation - for example, lower body is running while the upper body can use a different animation or inverse kinematics - shooting at an enemy during the run is a good example for that).
Now finally you get to the code part.
You need to build a system that will associate the animations to the skeleton and render it correctly.
This system also needs to be able to blend between animations and IK (for example - shifting between standing to running), and be able to combine several animation and partial animations - for example, walking (full body animation), looking at someone (IK for the upper body), waving a hand (IK with partial animation) and breathing (partial animation) at the same time would combine 4 different partial or full blendings.
I did not mention the fact that you need to build the importer and there is also a difference between action and the animation for the action.   Action can have several animations combined or picked randomly - they will be associated via a data mapping file.
I would suggest taking a look at XNA - it has many examples, importers and much more and contains a lot of the basic stuff in libraries so you don't have to start from scratch.
As people also mentioned - Blender3D is a good choice for editor+ and so might be Torque just for the experience of a game engine.
One last word - if you are going to try it out, it's not going to be a walk in the park, but hey - so much fun and the results will make you proud of yourself.

A: Take a look at the Blender Game Engine Tutorials, and also their Project Apricot, which was an open project to create a 3D game with the Blender Game Engine.

A: 3D character creation and programming of your 3D game are two distinct processes.
Usually you sculpt your 3D character in a 3D modeler (Blender, Maya, 3D studio Max, etc), you export this character to a file (.obj, .md2, etc) and you have written the code to your 3D game in order to handle the import of the character in your engine.
While this sounds quite difficult, 3D game engines do support all those stuff without writing millions line of code and re-inventing the wheel.
Take for example Ogre3D, a 3D open source game engine. You don't have to be a programming guru in order to have a simple example up & running in minutes. I suggest you take a look at their wiki and their tutorials.
For example this is a simple tutorial for creating and exporting your simple models from 3D Studio Max and importing them to Ogre 3D

A: I don't have a lot of game programming experience myself but I have found the XNA framework and resources pretty enlightening. You can find ton of examples and how to's and a pretty helpful forum here http://creators.xna.com/en-US/

A: Most of the information, like characters movements, is actually stored outside the code. It's quite a simple process actually:

*

*An artist makes a 3D model in Maya or whatever, and then saves it in a file. Let's say they called it 'Gollum.3D'.

*Now 'Gollum.3D' contains a whole lot of numbers representing the model points, textures and everything else.

*The program code then reads the file 'Gollum.3D' - all of its model points, textures and everything, and then does a lot of maths to calculate what the 3D scene is going to look like given all the numbers representing the model.

It turns out that everything in a game ends up being stored separately from the code, and the code just reads it and combines it all together when the game is run. When I say everything - I mean EVERYTHING! All of the text, the stats for the hit points and weapon damage amounts, the menu screen images, and even the artificial intelligence is stored separately from the program code in scripts. The program code ends up doing very little.
You may have heard of people making mods to games. Modders are people who edit the data that sits outside of the program code, which in turn changes the game to how it suits them. They're just taking advantage of the fact that basically everything about a game (except for a few core things) are not written into the program's code.

A: Animations can be done from within the 3D modeling software, and then its up to the code to 'run' different animations based on game logic.  The models get from the modeling software into the game through common formats.  For example, the XNA framework can natively read some of the most common model formats.

A: You should use a 3D rendering engine. A lot of them are free (Ogre3D is a good one) and usually they have facilities to import nearly any type of mesh created from common modeling software.

A: Visit Unity3d.com and you will be making your game in no time. Animations are done in the modeling software Maya, etc, but some are done in the engine. Unity makes physics easy and you are more or less creating your world and linking how objects interact.
Example - You have a camera -> You can set the camera from the UI to follow the main character and the XYZ transformation of where the camera is placed. It can also be done visually.
Check it out it is a lot of fun and less code then you would imagine. From there you can of course write your own code to do your own unique gameplay. It's easily explained as writing a script and dragging it onto the object you want the script to run on.
That's about as layman as I can get.  Cheers.

A: Since this topic is seeing new life, I figured I'd contribute.  I have been using Autodesk 3Ds Max for over 12 years producing 3D products and focused more on the animation side but do know that Autodesk provides an extensive library of classes with advanced scripting modules and capabilities built-in that has all the tools to write a 3D game within this program.  You would, of course, have to learn "Max Script" and how to interface with such built-in packages with names like "Biped", "Particle Flow", the "Havoc" reality simulation engine, etc, not to mention the render engine (usually the default scanline, Mental Ray, VRay) which will need a lot of parameters.
If you don't have a budget or are into open source, check out Blender!  It's amazing what this open-source 3D software and community has to offer.  They even have a "game engine" that can hook into it as well:  http://www.blender.org/features/ They have resources to help get you started.
I want to add to also mention that Unreal looks pretty promising, since they released it for "free" just read the fine print about 5% royalty if your game actually takes off!  https://www.unrealengine.com/what-is-unreal-engine-4

A: I find it peculiar that there are so many links for learning specific tools. If I were going to learn game development I'd want a general forum/site for this purpose. Such as GameDev.net.
PS: This is intended as a complementary answer, not a full one.

A: Think a while about how you do this all in 2D, it's pretty much same with 3D, the algorithms are just different and there's different aspects to care about.
The rest of what you ask is a design question and is dependent for game and the programmer. One may write a complex simulation for moving their characters, while someone else may rely only to skeletal animations. Someone may store game logic along 3d models and others just don't.
Examples? Perhaps quake source code is a good source to look into.

A: Writing a game engine is a complex task, my suggestion is to use one of the existing engines, (pick from the list: http://www.devmaster.net/engines/).
When picking the engine you need to take in account the following:

*

*License (you want to publish, do you have a budget, is it open source)

*Programming Language/Scripting (which language are you most comfortable with)

*Target platform (Windows/Linux/Mac/Console/Phone)

*Pipeline (are the exporters from your 3D modeling tool and importers into the engine)

Your question is more related to the last item, you should pick an engine that can import assets you produce in say 3DS, Maya into the engine in a way you don't have to worry with file formats, because that will make you more productive since you are only focusing into the game.

A: I didn't notice too many responses on what exactly to look for. In recent years there has been a lot more information released on how to do this somewhat easier, still pretty complex.
Free

*

*http://cgi.tutsplus.com/categories/3d-studio-max (mixed bag of free and paid content)

*http://unity3d.com/learn (between tutorials and documentation)

*https://www.youtube.com/user/UnrealDevelopmentKit/playlists (free tutorials for the Unreal Engine)

*https://docs.unrealengine.com/latest/INT/ (Unreal engine documentation)

Paid

*

*http://www.pluralsight.com (for coding and utilizing Unity with C#)

*http://www.digitaltutors.com (modeling, content creation, Unreal, and some Unity tutorials)

*http://www.gnomon.com (modeling and content creation)


text:
Q: Where is tortoisesvn-settings-network-enableProxyServer stored? I want to copy all tortoisesvn network  settings from one machine to another. Where are these stored?
I did this,
Save:
reg save HKEY_CURRENT_USER\Software\TortoiseSVN %USERPROFILE%\Desktop\tortoise.hive
Restore:
reg restore HKEY_CURRENT_USER\Software\TortoiseSVN %USERPROFILE%\Desktop\tortoise.hive
but it can not copy the enable proxy server  value correctly ,it always not checked.
so how can I get the correctly enable proxy server value, or what is the registry value of the enable proxy server?
thanks!
-----------------edit--------------------------
I still can not found the enable proxy server registry. I read the docs, set the http-proxy is ok, but there is no place to set enable proxy server that what I want to know !
like this :