text:
Q: Event based testing for android I'm using robotium for testing and I'm running into a bunch of timing issues that are making it difficult for me to know when an activity (or view) is done loading. As a result the tests I'm writing are not very robust.
I'm looking for a way to instrument my application under test with events that can be pushed to the test framework. If my application under test could "tell" my tests when an expect event occurs, this would be very useful. I've used Event Tracing for Windows  for windows\windows phone in the past to great effect.
The poor mans way of doing this that I'm looking at is to have my test application read the logcat in realtime and notify the test when an expected event occurs.
Does anyone have any other ideas?

A: To solve this I'm relying on the OS logcat. I instrument portions of the code being tested with trace messages and wait for them to occur in the test code. Its perhaps not the most performant way of doing things, but it suits my needs. I first tried to make an asynctask that read from the logcat, but ran into timing issues. I finally implemented something like this:
    logger.info("Click on something");
    EmSingleton.get().setCheckPoint();
    solo.clickOnText(SOMETHING, 1, true); // writes RELOAD_COMPLETE to logcat when done

    logger.info("Validate that the event is done);
    EmSingleton.get().waitForEvent(GrouponLnConstants.TodaysDeal.RELOAD_COMPLETE, 15000);
    // Do other stuff...

EventManager code (That I wrapped in a singleton called EmSingleton):
public class EventManager {
private ArrayList<String> args = null;
private long startTime;

public EventManager() {
    args = new ArrayList<String>(Arrays.asList("-v", "time", "-d"));
    setCheckPoint();
}

public EventManager(ArrayList<String> _args) {
    this();
    for(String s: args) {
        if (!args.contains(s)) {
            args.add(s);
        }
    }
}

public void setCheckPoint()
{
    Time startTimeOS = new android.text.format.Time();
    startTimeOS.setToNow();
    startTime = startTimeOS.toMillis(true);
}

public LogEvent checkEvent(String filter) throws Exception {
    ArrayList<LogEvent> events = gatherEvents();

    for(LogEvent event: events){
        if(event.checkMsgSubstring(filter)){
            return event;
        }
    }

    return null;
}

public LogEvent waitForEvent(String filter, int timeout) throws Exception
{
    int retries = timeout/1000 == 0 ? 1 : timeout/1000;
    for(int i = 0; i < retries; i++)
    {
        LogEvent event = checkEvent(filter);
        if(event != null){
            return event;
        }
        Thread.sleep(1000);
    }
    return null;
}

public ArrayList<LogEvent> getEvents() {
    return gatherEvents();
}

public void clearEvents() throws Exception{
    ArrayList<String> commandLine = new ArrayList<String>();
    commandLine.add("logcat");
    commandLine.add("-c");

    ProcessBuilder pb = new ProcessBuilder(commandLine.toArray(new String[0]));
    pb.redirectErrorStream(true);
    Process logcatProcess = pb.start();

    logcatProcess.waitFor();
}

protected ArrayList<LogEvent> gatherEvents() {
    ArrayList<LogEvent> events = new ArrayList<LogEvent>();
    final StringBuilder log = new StringBuilder();
    BufferedReader br;
    try {
        ArrayList<String> commandLine = new ArrayList<String>();
        commandLine.add("logcat");
        if (null != args) {
            commandLine.addAll(args);
        }

        ProcessBuilder pb = new ProcessBuilder(commandLine.toArray(new String[0]));
        pb.redirectErrorStream(true);
        Process logcatProcess = pb.start();

        InputStream is = logcatProcess.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        br = new BufferedReader(isr);

        String line = null;

        while (true) {
            line = br.readLine();
            if(line == null){
                break;
            }
            // Add events to the events arraylist if they occur after the LogCollector has started to run
            LogEvent event = new LogEvent(line);
            if(event.peekTimeMS() > startTime)
            {
                events.add(event);
            }
        }
    } catch (Exception e) {
        TestLogger.get().error("GrouponTest", String.format("gatherEvents doInBackground failed: %s", e.toString()));
    }

    return events;
}
}

You'll need to set the following permission in your application:
<uses-permission android:name="android.permission.READ_LOGS">

I also created a LogEvent Object to parse events coming from the logcat:
public class LogEvent {
String orignalString = null;
boolean parsed = false;

long timeMs = 0;
String timeString = null;
String verbosity = null;
String tag = null;
int pid = 0;
String msg = null;

// Lazy factory design pattern
// http://en.wikipedia.org/wiki/Lazy_initialization
public LogEvent(String s) {
    orignalString = s;
}

public long getTimeMs() {
    checkInit();
    return timeMs;
}

public long peekTimeMS()
{
    // Time is always formattted as such: MM-DD HH:MM:SS.XXX
    return parseTime(orignalString.substring(0,5), orignalString.substring(6,18));
}

public String getTimeString() {
    checkInit();
    return timeString;
}

public String getVerbosity() {
    checkInit();
    return verbosity;
}

public String getTag() {
    checkInit();
    return tag;
}

 public int getPid() {
    checkInit();
    return pid;
}

public String getMsg() {
    checkInit();
    return msg;
}

/**
 * Checks to see if the event message contains a substring
 * @param check
 * @return
 */
public Boolean checkMsgSubstring(String check)
{
    int index = orignalString.indexOf(check);
    boolean isSubstring = (index >= 0);
    return isSubstring;
}

public String toString()
{
    checkInit();
    return String.format("%s %s/%s(%d): %s", timeString, verbosity, tag, pid, msg);
}

private void checkInit()
{
    if(!parsed)
    {
        parseEvent();
        parsed = true;
    }
}

private void parseEvent()
{
    try{
    String [] splits = orignalString.split("[ ]+");
    // Sometimes the PID is of format ( XX) instead of (XX)
    if(splits[2].indexOf(")") < 0)
    {
        splits[2] += splits[3];
        ArrayList<String> formatted = new ArrayList<String>(Arrays.asList(splits));
        formatted.remove(3);
        splits = formatted.toArray(new String[formatted.size()]);
    }

    // Parse time
    timeMs = parseTime(splits[0], splits[1]);
    timeString = String.format("%s %s", splits[0], splits[1]);
    // Parse tag
    verbosity = parseVerbosity(splits[2]);
    tag = parseTag(splits[2]);
    pid = parsePid(splits[2]);
    // Parse message (may be empty)
    if (splits.length > 3) {
        msg = orignalString.substring(orignalString.indexOf(splits[3]));
    } else {
        msg = "";
    }
    }
    catch (Exception e)
    {
        // TODO: there are some strangely formated events in the system. need to deal with these?
    }
}

/**
 * Time comes in following format: 08-11 20:03:17.182:
 * Parse into milliseconds
 * @param day string of format 08-11
 * @param hours string of format 20:03:17.182:
 * @return
 */
private long parseTime(String day, String hours)
{
    Time timeToSet = new Time();
    Time currentTime = new Time();
    currentTime.setToNow();

    // Parse fields
    String[] daySplits = day.split("-");
    if(daySplits.length < 2)
        return 0;

    String[] hourSplits = hours.split(":");
    if(hourSplits.length < 2)
        return 0;

    String[] secondSplits = hourSplits[2].split("\\.");
    if(secondSplits.length < 2)
        return 0;

    int _year = currentTime.year;
    int _month = Integer.parseInt(daySplits[0])-1;
    int _day = Integer.parseInt(daySplits[1]);
    int _hour = Integer.parseInt(hourSplits[0]);
    int _min = Integer.parseInt(hourSplits[1]);
    int _sec = Integer.parseInt(secondSplits[0]);
    int _mili = Integer.parseInt(secondSplits[1]);

    //set(int second, int minute, int hour, int monthDay, int month, int year)
    timeToSet.set(_sec, _min, _hour, _day, _month, _year);

    // return calculated value
    long parsedTimeInMili = timeToSet.toMillis(true) + (long)_mili;
    return parsedTimeInMili;
}

private String parseVerbosity(String s)
{
    return s.split("/")[0];
}

private String parseTag(String s)
{
    int verbosityLength = parseVerbosity(s).length() +1;
    String tagPart = s.substring(verbosityLength);
    return tagPart.split("\\(")[0];
}

private int parsePid(String s)
{
    try {
        String pidPart = s.split("\\(")[1];
        return Integer.parseInt(pidPart.split("\\)")[0]);
    } catch (Exception e) {
        e.toString();
    }
    return -1;
}
}


text:
Q: Rails: "You have a nil object when you didn't expect it" In my controller:
Article.author_ids_in(params[:filters][:author_ids])

This of course returns an error ("You have a nil object...") if those particular params have not been passed.  Here is the model method:
def self.author_ids_in(filters)
  unless filters.nil?
    where(:author_id + filters)
  else
    scoped
  end
end

As you can see, I'm already prepared for a nil object, so how can I get Ruby to allow nil to be passed?

A: params[:filters] is most likely nil so it's raising an exception when you try to go into it to get [:author_ids]
Either check before you call the scope, or rescue the exception:
begin
  Article.author_ids_in(params[:filters][:author_ids])
rescue NoMethodError
  # do something else here
end

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use external PHP file in laravel blade.php file? I want to include external PHP file (pdate.php) in Laravel and use it in blade.php file. How can I do it?
The PHP file imported in app\date\pdate.php  folder and by using app_path() function in controller I try to send it in blade.php but there is error.
public function index(){
  include_once(app_path() . '/date/pdate.php');
  return view('/cashWithdraw/create');
}

When I use one variable of that file in blade.php I will get this error.

Undefined variable: today (View: E:\laravelProject\deal\resources\views\cashWithdraw\create.blade.php)

A: In composer.json file you just add needed files in "autoload" section – in a new entry called files:
 "autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/date/pdate.php"
    ]
},

after that run this command composer dump-autoload now you can use any function in this file globally

A: This can easily be done using the blade @include() helper. If you save your file as a pdate.blade.php file, for example in resources/views/date, then you can include it as follows:
Inside of cashWithdraw/create.blade.php:
@include("date/pdate")

The only catch is that the variables available in pdate.blade.php need to be defined, but that can be done in a number of ways:
Directly in pdate.blade.php:
@php $today = \Carbon\Carbon::now(); @endphp

In the controller that returns create.blade.php:
public function index(){
  $today = \Carbon\Carbon::now();
  return view('cashWithdraw.create')->with(["today" => $today]);
}

In the @includes within create.blade.php:
@include("date/pdate", ["today" => \Carbon\Carbon::now()])

A: You aren't passing any variables into your view.  You will need to pass any variables generated by pdate into the view.
public function index(){
    include_once(app_path() . '/date/pdate.php');

    return view('/cashWithdraw/create', [
        'today' => $today
    ]);
}

The only variables that will be available in your blade are the ones you pass in there.

A: If your file is a class, you can inject it into a view by using service injection as follows:
@inject('pdata', 'app\date\pdate')

then invoke any method. Assuming your class has one like getMyDate:
<div class="anything">
   {{ $pdata->getMyDate() }}
</div>


text:
Q: Heroes 4 castle siege mechanics After searching the internet, I cannot find the exact mechanics of castle siege in Heroes 4.
Browsing through some websites in English and Russian I have found that units on the towers get 100% increased attack and defense. Is this correct? Are there any other effects compared to the regular combat? Based on my experience I suspect that regular troops inside the castle walls (not on tower) also get certain bonuses? Is there a reference somewhere?


text:
Q: Function finding the deepest sum of a binary search tree I'm trying to make a function in python were I don't want to change the BST class at all to do this. The function is to find the sum of the path of the root to the node with the highest depth. If there is multiple nodes that have the same depth I'm looking for the maximum sum of that and return it.
What I got so far (Using a basic BST Class)
class BTNode(object):
    def __init__(self, data, left=None, right=None):

        self.data = data
        self.left = left
        self.right = right

After trying to make an algorithm to solve this for a while, I came up with a couple above but they were fails and I didn't know how to code it.
ALGORITHM:
I think this would work:
We start from the root. (The base case I think should be whenever we hit a leaf as in when there is no child in a node so no left or right child, and also when there is a left no right, or when there is a right no left)
I check the left subtree first and get the depth of it, we'll call it depth_L as well with the sum. Then I check the right subtree and we will call it depth_R then get the depth of it and its sum.
The second condition would be to check if they are equal, if they are equal then its easy and we just take the max sum of either two depths. Else we would see who has the highest depth and try to get the sum of it.
Now were I don't know how to do is a couple things.
1: I never learned optional parameters so I'm trying to avoid that while trying this exercise but I don't think I can and I'd really appreciate someone could show me some cool helper functions instead.
2: Its not the total sum of the right side or the left side its the path that I need. Its kind of confusing to think of a way to get just the path
(Heres my renewed attempt using the algorithm above):
    def deepest_sum(self, bsum = 0, depth = 0):

        # The root is in every path so
        bsum = bsum + self.data
        depth = depth + 1
        # Base case whenever we find a leaf
        if self.left == None and self.right == None:
            result = bsum,depth

        elif self.left is not None and self.right is None:
            pass

        elif self.left is None and self.right is not None:
            pass

        else:

            # Getting the left and right subtree's depth as well as their
            # sums, but once we hit a leaf it will stop
            # These optional parameters is messing me up
            if self.left:
                (sums1, depth_L) = self.left.deepest_sum(bsum,depth)
            if self.right:
                (sums2, depth_R) = self.right.deepest_sum(bsum,depth)

            # The parameter to check if they are equal, the highest goes through
            if depth_L == depth_R:
                result = max(sums1, sums2), depth_R
            else:
                if depth_L > depth_R:
                    result = sums1, depth_L
                else:
                    result = sums2, depth_R

        return result

Stuck on the parts i mentioned. Heres an example:
>>> BST(8, BST(7, BST(10), BST(11)), BST(6, BST(11), BST(9, None, BST(14)))

37  (depth 3 is the highest so 8 + 6 + 9 + 14 is the path)

Sorry i put BST i just forgot, its a binary Tree not BST.
I know mine gives a tuple but I can always make a helper function to fix that, I just thought it'd be easier keeping track of the nodes.

A: You could simplify the implementation quite a bit if the function doesn't need to be a method of BTNode. Then you could keep track of the depth & sum, iterate past the leaf and return the current depth and sum. Additionally if you return (depth, sum) tuples you can compare them directly against each other with max:
class BTNode(object):
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

def deepest_sum(node, depth=0, current=0):
    # Base case
    if not node:
        return (depth, current)

    depth += 1
    current += node.data

    return max(deepest_sum(node.left, depth, current),
               deepest_sum(node.right, depth, current))

tree = BTNode(8, BTNode(7, BTNode(10), BTNode(11)), BTNode(6, BTNode(11), BTNode(9, None, BTNode(14))))
print(deepest_sum(tree))

Output:
(4, 37)


text:
Q: Get height of string with font I am having the hardest time figuring out how to get the size, specifically the height, of a UILabel containing specified text and using a specified font. Basically, I want a method that returns the height for a given string and font.
This is what I have so far:
+ (CGFloat)heightForString:(NSString *)string withFontSize:(CGFloat)size
{
    NSDictionary *attributes = @{NSFontAttributeName : [UIFont systemFontOfSize:size]};

    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:string
                                                                           attributes:attributes];
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;

    CGRect paragraphRect =
    [attributedText boundingRectWithSize:CGSizeMake(screenWidth, CGFLOAT_MAX)
                                 options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                 context:nil];

    return paragraphRect.size.height;
}

This returns a height that is about half the size it should be. I know this question has been asked a million times, but none of the solutions work fully.

A: Use this category to calculate height of text with given font and max width, which is used in in SOMessaging
Basically I made it as replacement of sizeWithFont:constrainedToSize:lineBreakMode method of iOS6

A: I have decided to simply create a dummy label, set it's text property and set numberOfLines to 0 and say [label sizeToFit] that will allow you to get the frame of the label, which includes the height. It's not an ideal way, but it works.
Apparently in iOS 8 there will be self sizing table view cells! Cannot wait!


text:
Q: Pip3 search finds intel-numpy, but can't install When I do a pip3 search intel-numpy it is found, but when I try pip3 install intel-numpy I get the error Could not find a version that satisfies the requirement intel-numpy. Anybody know how to fix this? I'm trying to limit this to command line operations as I want to add it to a Dockerfile.

A: In the list of downloadable files there are only 64-bit wheels for Python 2.7 and 3.6, and no source files. Either you have a different version of Python or a different (32-bit) architecture. Or both.


text:
Q: advantage of WSO2 AS instead of other application servers Why would anyone use WSO2 Application Server instead of other application servers?
I rather encountered only problems with it, mainly due to class loading issues, so I would appreciate if someone could point out what are the advantages or the use cases when using WSO2-AS really makes a difference.
I can see the benefits of other standalone WSO2 products, but as far as the AS is concerned, I would rather rely on more lightweight servers and just package the libraries I need.

A: There are number of advantages on WSO2 Application Server.
1.) It provides in-built support for multi-tenancy, in case if you have isolated departments like organization there is no real need to have number of server instances you could simply create a new tenant.
2.) Automatic lazy loading support for tenants, web applications and web services. In a production system a particular tenant/web application/web service can be ideal for sometime it's a waste to allocate hardware resources continuously to such ideal applications specially if you use IaaS. WSO2 application server can detect such ideal  tenant/web application/web service and release their resources and tenant/web application/web service will load again when a new request dispatch to the particular tenant/web application/web service.
3.) Wide range of deployment options, support to deploy on-premise, public or private IaaS , public or private PassS such as Apache Stratos. An an example one can deploy his application into WSO2 App Cloud (http://wso2.com/cloud/app-cloud/) instantly without downloading anything, later he can get same experience one of above platforms.
4.) Deployment synchronization  feature, a clustered environment you may have very large number of nodes and upgrading application version and configuration changes across the cluster can be headache. Using Deployment synchronization feature you can modify only one node labeled as manger node and Deployment synchronization will take care about synchronize changes across the cluster automatically and consistently.
5.) When developing applications on WSO2 Application Server you can leverage carbon platform level features such as identity, registry, logging, distributed caching, multi-tenancy etc. As an example one can use identity features provided by the platform to mange users, roles permissions also for authentication and authorization without write something own.
6.) Inbuilt support for security standards such SSO among other WSO2 products.
7.) In-build monitoring capability for web services and web application through WSO2 BAM.
8.) Enhanced and rich dashboard for applications and services which facilitate to basic statistics, application management, security wizards, code generations, Try -It tools, run time logging configurations etc.
9.) Enhanced classloading mechanism (starting from AS 5.1.0), within one Application server instance you can have number of virtual server environments per application level. As an example one can specify an application run on minimal Tomcat mode or can assign to run Carbon mode which is ( Tomcat + Carbon platform).
When it come to your specific issue if you can specify your Application Server version and elaborate more on your classloading issue I can provide you more specific answer.
Having said above I want to mention that I'm from WSO2.


text:
Q: Interaction.GetBehaviors from FrameworkElementFactory type combobox I'm trying to hide a dynamic combobox what is set from FrameworkElementFactory.
If i try Combobox as parameter then i get the error 'ComboBox' is a type, which is not valid in the given context and if i try fElement as parameter then it gives the error "cannot convert from 'System.Windows.FrameworkElementFactory' to 'System.Windows.DependencyObject'" I need the solution in C# not in xaml or ASP.net.
 FrameworkElementFactory fElement = new FrameworkElementFactory(typeof(ComboBox));

       fElement.SetValue(ComboBox.WidthProperty, 125D);
            fElement.SetValue(ComboBox.ItemsSourceProperty, choices);
            fElement.SetValue(ComboBox.DisplayMemberPathProperty, "Value");
            fElement.SetValue(ComboBox.SelectedValuePathProperty, "Value");
            fElement.SetValue(ComboBox.NameProperty, "CONAAM" + rowOnderdeel.OnderdeelID);
            //fElement.SetValue(ComboBox.NameProperty, Onderdeelnaam);
            fElement.AddHandler(Selector.SelectionChangedEvent, new SelectionChangedEventHandler(cbCursistOnderdeelResultaat));
            fElement.SetBinding(ComboBox.TextProperty, bind);
            Interaction.GetBehaviors(ComboBox).Add(new HideComboxBehavior());

A: Solutions was to use System.Windows.Style and use setter to trigger the visibility of the combobox.
FrameworkElementFactory fElement = new FrameworkElementFactory(typeof(ComboBox));
                    fElement.SetValue(ComboBox.WidthProperty, 125D);
                    fElement.SetValue(ComboBox.ItemsSourceProperty, Resultaten);
                    fElement.SetValue(ComboBox.DisplayMemberPathProperty, "Value");
                    fElement.SetValue(ComboBox.SelectedValuePathProperty, "Key");
                    fElement.SetValue(ComboBox.SelectedValueProperty, new Binding(column.ColumnName));

                    Style cbStyle = new Style(typeof(ComboBox));
                    Setter cbSetter = new Setter(ComboBox.VisibilityProperty, Visibility.Visible);
                    cbStyle.Setters.Add(cbSetter);

                    DataTrigger cbDataTrigger = new DataTrigger();
                    Binding cbBinding = new Binding(column.ColumnName);

                    cbDataTrigger.Value = 0;

                    Setter cbDataSetter = new Setter(ComboBox.VisibilityProperty, Visibility.Hidden);

                    cbDataTrigger.Setters.Add(cbDataSetter);
                    cbDataTrigger.Binding = cbBinding;
                    cbStyle.Triggers.Add(cbDataTrigger);

                    fElement.SetValue(ComboBox.StyleProperty, cbStyle);

                    DataTemplate dataTemplate = new DataTemplate();
                    dataTemplate.VisualTree = fElement;
                    gvc.CellTemplate = dataTemplate;


text:
Q: What's the difference between Refresh, Update and Repaint? I don't know which of those three methods suits me most. They all work for me. Does anyone know the difference between Refresh, Update and Repaint?

A: According to the online documentation:
Refresh - Repaints the control on the screen.

Call Refresh method to repaint the
control immediately. Refresh calls the
Repaint method. Use the Refresh and
Repaint methods interchangeably.

Repaint - Forces the control to repaint its image on the screen.

Call Repaint to force the control to
repaint its image immediately. If the
ControlStyle property includes
csOpaque, the control paints itself
directly. Otherwise, the Repaint
method calls the Invalidate method and
then the Update method so that any
visible portions of controls beneath
the control will be repainted as well.

Update - Processes any pending paint messages immediately.

Call Update to force the control to be
repainted before any more, possibly
time-consuming, processing takes
place. Use Update to provide immediate
feedback to the user that cannot wait
for the Windows paint message to
arrive.
Update does not invalidate the
control, but simply forces a repaint
of any regions that have already been
invalidated. Call Repaint instead to
invalidate the control as well.

A: Per an older (CBuilder 6) VCL reference:
Invalidate  "Invalidate informs a control that its entire surface needs to be repainted. Calling Invalidate can prevent flicker caused by a series of partial repaints. There is no performance penalty for calling Invalidate multiple times before the control is actually repainted".
The actual repaint does not occur until the control is updated. To force an immediate repaint, call Repaint instead.
Repaint "TWinControl::Repaint calls the Invalidate method and then the Update method to repaint the control" (slight paraphrase).
(Sadly, the older reference is better and more complete than the newer reference I have (CBuilder 2007).

A: Your question is already answered, but if you need good performance and less flicker you should call Invalidate instead. It allows Windows to optimize the painting process.
Invalidate - Completely repaint control.

Use Invalidate when the entire control
  needs to be repainted. When more than
  one region within the control needs
  repainting, Invalidate will cause the
  entire window to be repainted in a
  single pass, avoiding flicker caused
  by redundant repaints. There is no
  performance penalty for calling
  Invalidate multiple times before the
  control is actually repainted.


text:
Q: Perform calculations in every file in the path with loop? i have a code that finds every file in the directory with a certain extension:
and i want this script to be applied to every shp:
import geopandas as gpd
pst = gpd.read_file(r'C:\Users\user\Desktop\New folder1\PST')#this is not needed in the final because it takes the path by it self
dbound = gpd.read_file(r'C:\Users\user\Desktop\New folder1\DBOUND')#same here
dbound.reset_index(inplace=True)
dbound = dbound.rename(columns={'index': 'fid'})
wdp = gpd.sjoin(pst, dbound, how="inner", op='within')#each dbound and pst from every subfolder
wdp['DEC_ID']=wdp['fid']

this is the  list that contains the paths to the shapefiles:
grouped_shapefiles that has these shapefiles:
[['C:\\Users\\user\\Desktop\\eff\\20194\\DBOUND\\DBOUND.shp',
  'C:\\Users\\user\\Desktop\\eff\\20194\\PST\\PST.shp'],
 ['C:\\Users\\user\\Desktop\\eff\\20042\\DBOUND\\DBOUND.shp',
  'C:\\Users\\user\\Desktop\\eff\\20042\\PST\\PST.shp'],
 ['C:\\Users\\user\\Desktop\\eff\\20161\\DBOUND\\DBOUND.shp',
  'C:\\Users\\user\\Desktop\\eff\\20161\\PST\\PST.shp'],
 ['C:\\Users\\user\\Desktop\\eff\\20029\\DBOUND\\DBOUND.shp',
  'C:\\Users\\user\\Desktop\\eff\\20029\\PST\\PST.shp'],
 ['C:\\Users\\user\\Desktop\\eff\\20008\\DBOUND\\DBOUND.shp',
  'C:\\Users\\user\\Desktop\\eff\\20008\\PST\\PST.shp']]

and i want something like this:
results = []
for group in grouped_shapefiles:

#here applies the script where i need help to connect in the loop
#and then the export process- the line that follows
#o=a path
out = o +'\result.shp'#here it would be nice to add to the name in the output the name of its folder so it would be unique
data2.to_file(out)

How can i do that?


text:
Q: How put button into variable when it appears after page onload How can I get the button add__deal__btn after it appears?  When the page loads add__deal__btn doesn't exist, but after I add the task__card to the div it appears. How can I manipulate the button after it appears?

let addTitle = document.querySelector('.add__title');
let addBtn = document.querySelector('.add__btn');
let tasks = document.querySelector('.tasks');
let addDealBtn = [];

addBtn.onclick = function() {
  let task = document.createElement('div');
  task.className = 'task__card';
  let taskTitle = document.createElement("h4");
  taskTitle.innerHTML = addTitle.value
  task.appendChild(taskTitle)
  addDealBtn = document.createElement("button");
  addDealBtn.className = "add__deal__btn";
  addDealBtn.innerHTML = "Add deal";
  task.appendChild(addDealBtn);
  tasks.append(task);
}

//THIS CODE DOESN'T WORK

addDeal = document.querySelectorAll('.add__deal__btn');

for(let i = 0;i<addDeal.length;i++){
 addDeal[i].onclick= function(){
   alert();
 }
}

  <input type="text" class="add__title">

  <button class="add__btn">Add</button>

Thank you

A: Add the onclick event when you create the button.

let addTitle = document.querySelector('.add__title');
let addBtn = document.querySelector('.add__btn');
let tasks = document.querySelector('.tasks');
let addDealBtn = [];

addBtn.onclick = function() {
  let task = document.createElement('div');
  task.className = 'task__card';
  let taskTitle = document.createElement("h4");
  taskTitle.innerHTML = addTitle.value
  task.appendChild(taskTitle)
  addDealBtn = document.createElement("button");
  addDealBtn.className = "add__deal__btn";
  addDealBtn.innerHTML = "Add deal";
  // Add onclick event here
  addDealBtn.onclick = function() {
      alert('Button clicked!');
  };
  task.appendChild(addDealBtn);
  tasks.append(task);
}

  <input type="text" class="add__title">

  <button class="add__btn">Add</button>

A: The line addDeal = document.querySelectorAll('.add__deal__btn'); only runs once (when the script loads). At that time, no <button> elements with class add__deal__btn exist in the DOM.
To achieve what you want simply add the event listener to each newly generated button. Like this:

let addTitle = document.querySelector('.add__title');
let addBtn = document.querySelector('.add__btn');
let tasks = document.querySelector('.tasks');

addBtn.onclick = function () {
  let task = document.createElement('div');
  task.className = 'task__card';
  let taskTitle = document.createElement("h4");
  taskTitle.innerText = addTitle.value;
  task.appendChild(taskTitle);
  let addDealBtn = document.createElement("button");
  addDealBtn.className = "add__deal__btn";
  addDealBtn.innerText = "Add deal";
  task.appendChild(addDealBtn);
  tasks.append(task);
  addDealBtn.onclick = function() {
    alert('Hey it works!');
  };
}

  <input type="text" class="add__title">

  <button class="add__btn">Add</button>

Tip: You don't need to create an array to store each new button you create anymore.


text:
Q: Regression testing for schema (xsd) equivalence I am thinking about rewriting a schema with lots of standalone complex types in it, into one where the complex types extend other base types more sensibly.  The rationale for this is partly conceptual - because most of these types are specific instances of a domain object with a definite hierarchical structure - and partly practical, because we're using JAXB-generated classes to handle the XML reading logic and it's impossible to write methods for common functionality without either reflection or a lot of instanceof and casting.  Bleh.
So my primary question is whether anyone is aware of a good way to test two XSD schemas for functional equivalence?  If I perform this schema refactoring correctly, the set of documents considered valid should be exactly the same for the two schemas despite the fact the files themselves would be very different.  This sounds like the kind of thing that a testing framework could help with; I know there are tools that will suggest test inputs for JUnit tests, and I was wondering whether there might be any tools to generate edge case XML documents to test for validity against the old and new schemata?
And as an aside - if this is a terrible idea (or if there are better alternatives), then stop me now. :-)
Thanks for your attention.

A: After some investigation, I've come across the Liquid XML Sample Generator, which sounds like exactly the kind of thing I'd be looking for (though I'm not sure quite how good this would be for testing edge cases).
I also stumbled across SUT: XML Schema Unit Test which does not look to be actively maintained any more, or well documented, but takes a more programmatic approach to defining what should be valid or invalid XML documents for a given schema, and testing this.  Unfortunately test cases seem to be interpreted linearly rather than permuting the possibilities for each distinct node as the above XML sample generator would do.  Consequently while it would be possible to enforce better coverage it would likely be a lot of work to do so.
So at least I have what appears to be a workable fallback - generating a bunch of documents from the old schema and then validating them against the new schema, and vice versa.  It's not definitive (well, unit tests never are anyway) but running a few hundred or thousand tests in each direction should give some pretty good confidence that the schemata are equivalent.
I would still be very happy to have an elegant testing solution presented, but after an hour of Googling I'm not holding out much hope that something along those lines exists.

A: there is no general answer to this problem, as the question of whether two context free grammars are equivalent is undecidable. See this wikipedia page.
There has been some theoretical work done on this, but there is no tool that is packaged off the shelf to do this for you.
You can solve this problem if you make certain assumptions about how to design your schema (forbidding anonymous types, naming conventions and so on). Then you can use a library like eclipse XSD (which works outside eclipse in a standalone app just fine) to perform the comparison.
Finally, here's a link to a research paper that discusses the problem in more detail.


text:
Q: Call between two or more devices which are connected with WiFi - iOS I don't know the that this question is easy or not, But I didn't found any thing related to this on the web.
Does anyone know the wifi library or other help having functionality of connecting two device with iOS and having functionality of creating call between these two connected device or we can create group and do the group call also?

A: Setup you own WebRTC server and obtain absolute URL with its protocol. Make sure that has to be work within your network only. When your devices are in wifi / network. They can connect each other through absolute URL.
Refer - https://github.com/ISBX/apprtc-ios/blob/master/README.md


text:
Q: %mprun keeps giving nameerror (Problem with imported modules) Hi I am currently trying to execute a line-by-line memory profile for one of my functions. However, whenever the function requires an imported module, the %mprun command does not work. This is a simplified example. I tried this both on jupyter, command prompt and anaconda prompt.
#Here I write a py file containing the function I want to profile
%%file mpruntest.py
@profile
import pandas as pd
import numpy as np

def test(a):
    df = pd.DataFrame(np.random.randn(10,5))
    return df

This will give me a py file called mpruntest.
#Here I run the mprun
from mpruntest import test
%mprun -f test test(1)

I keep receiving NameError stating that pd or np is not defined. I am not sure how I should go about this so that the memory profiler can work and read that the relevant modules are imported.


text:
Q: Advantages of subtyping over typeclasses What are the advantages of OOP subtyping over typeclasses, if any? In other words, now that we have typeclasses, is there any reason to still use OOP subtyping?
PS: I am a Scala programmer.

A: Personally, I find OOP easier to deal with within the constraints of what it handles well. In other words: in cases where you don't actually need typeclasses, I find objects easier to understand.
However, this might just be an artifact of the syntactic overhead that the typical typeclass embedding of objects has. If Haskell had syntactic sugar for some common kinds of typeclass patterns, that difference would probably vanish.
What I find more interesting, is the fact that the Haskell community shows that typeclasses are more powerful than objects, since there exists a trivial embedding of objects in typeclasses, but typeclasses can do things objects can't. The Scala community, however, shows that objects are at least as powerful as typeclasses1, since there exists a trivial embedding of typeclasses in objects.
This seems to indicate that the relationship between the two is much more intimate than commonly thought.

1 See Type Classes as Objects and Implicits by Bruno C.d.S. Oliveira, Adriaan Moors and Martin Odersky, as well as the discussion of that paper on Lambda the Ultimate, especially this nice summary by Paul Snively (emphasis added):

Martin Odersky and team's design decisions around how to do type classes in a unified OO and FP language continue to bear fascinating fruit. Implicits look less and less like "poor man's type classes," and more and more like an improvement upon type classes, in my opinion given a quick read of this paper.

A: In a language that is not purely functional, subtyping lets you have different side-effects with the same usage; this isn't always easy to achieve with type classes.  (You can achieve it, of course; it just seems more awkward to me.)
Also, subtyping can be more efficient--it's a way to cache the information that "X is a Y" without requiring repeated conversion (or compiler heroics to cache that information) of X to Y.  For very deep hierarchies, this could possibly be an issue.

A: This might help:
http://www.haskell.org/haskellwiki/OOP_vs_type_classes

A: One more difference for Scala at least is that chains of subtypes just work, whereas chains of typeclasses are much tricker.  If we have types A, B, and C, then if A < B and B < C then necessarily A < C.  However, if A <% B and B <% C it is not necessarily the case that A <% C.  This is because the Scala compiler will not apply multiple implicit conversions, as otherwise type-inference because difficult and (IIRC) potentially undecideable.

A: A pragmatic reason to continue support for OOP is interoperability. One of the currently ongoing questions in the BitC discussion is whether to add single inheritance to the language. There are pragmatic pros and cons, and also issues pro and con in its implications for the formal type system and type inference.
For a while, the instance resolution mechanism for type classes had us convinced that type classes were fundamentally flawed for lack of link safety. In the absence of a lexically scoped resolution mechanism, type class instance resolution fails to scale in human terms: a change by one development group can cause linkage errors in an application written in another place by a completely different group. That had us reluctantly looking at single inheritance and some form of F<+SelfType sort of scheme. There are related concerns when instances have multiple resolutions with different degrees of specialization.
We have since come to an approach to instance resolution that looks to resolve this problem to our satisfaction. The question we are wrestling with now is (a) whether BitC programs need subtyping, and if so for what, and (b) even if we don't, whether interoperability with programs in OO languages may nonetheless require us to support a type system in which inheritance is expressible, and consequently a language in which it can be used.
None of which is any sort of conclusive answer to the OP's question. The point, I suppose, is that the issues here go beyond the design of any particular language. There are also human factors and interoperability concerns to be considered.
Jonathan Shapiro

A: At present, the syntactic overhead of Scala type classes is a good bit larger than for subtyping via trait inheritance, as is the potential runtime overhead.  Imagine a case where you need to have fifty different types of events conform to an interface to support an event processing engine.  Much easier to write
class MyEvent extends Event{
  val name = "foo"
}

than
class MyEvent{
   val name = "foo"
}

object MyEvent2Event{
   implicit def convert(myEvent:MyEvent) = new Event{ val name = myEvent.name}
}

The second form allows a lot more flexibility in terms of post-hoc polymorphism, freedom of naming, and general bad-assery, but typing out those fifty conversion methods and then doing the appropriate imports when the typeclass is needed is going to get to be a right pain.  If you don't need the flexibility, it's tough to see the payoff.  Plus there's that nagging "new" keyword in the second, which will spawn endless "is this overstressing the garbage-collector" arguments.
The situation is worse for mixin inheritance that introduces mutable state.  Consider the following trait, taken from production code:
trait Locking{
   private val lock = new ReentrantReadWriteLock()

   def withReadLock[T](body: => T):T={
      try{
         lock.readLock.lock()
         body
      }finally{
         lock.readLock.unlock()
      }
   }
   // same for withWriteLock
}

Incredibly handy use of mixin inheritance, and not really doable with Scala type classes, due to the presence of the "lock" val.  Where should it go? If you put it in the adapted class, you lose most of the encapsulation value of the trait.  If you put it in the adapter code, the locks no longer protect anything, since you'd be locking on different lock objects every time you're adapted.


text:
Q: Не работает bootstrap markdown Сделано все по инструкции, самое меню показывает которое прописано тут
<textarea class="form-control" id="text" data-provide="markdown-editable" data-provide="markdown" name="text" rows="3" placeholder="Введите текст сообщения"></textarea>

А вот текст который выводится не форматирует под ббкоды
 <div data-provide="markdown-editable">
    <?php echo nl2br($item['message']) ?>
 </div>

Как решить проблему ?


text:
Q: Get a DateTime with an specific pattern with nscala-time I am trying to get this pattern 'dd-MM-yyyy' with a variable of type DateTime
@{DateTimeFormat.forPattern("dd-MM-YYYY").parseDateTime(user.birthday.toString)}

But I am getting this error

java.lang.IllegalArgumentException: Invalid format: "2015-12-10T00:00:00.000Z" is malformed at "15-12-10T00:00:00.000Z"

Is there a way to do this with nscala-time?
makes a difference if I am using UTC?
UPDATE
For the moment I am casting to Date and doing this
@{Dates.format(user.birthday.toDate, "dd-MM-YYYY")}

But maybe is a better way without casting
thank you

A: So, if I understood your question correctly, you are trying to achieve the following:

*

*Parse date from a string using a date format

*Print/Display the date in another format.

Try the below:
@{Dates.format(DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parseDateTime(user.birthday.toString), "dd-MM-YYYY")}


text:
Q: why no overflow warning when converting int to char int i=9999;

char c=i;

gives no overflow warning, While
char c=9999;

gives,

warning C4305 initializing  truncation from int to char

why no overflow warning when converting int to char?

A: You'll get warning C4244 when compiling with /W4 (which you should always do).

warning C4244: 'initializing' : conversion from 'int' to 'char', possible loss of data

A: Whether any code construct produces a warning is up to the cleverness of the compiler and the choices made by its authors.
char c=9999;

9999 is a constant expression. The compiler can determine, just by analyzing the declaration with no additional context, that it's going to overflow. (Presumably plain char is signed; if it's unsigned, the conversion is well defined -- but a compiler could still choose to warn about it.)
int i=9999;

char c=i;

This has the same semantics, but for a compiler to warn about the initialization of c, it would have to know that i has the value 9999 (or at least a value outside the range of char) when it analyzes that declaration.  Suppose you instead wrote:
int i = 9999;
i = 42;
char c = i;

Then clearly no warning would be necessary or appropriate.
As James McNellis's answer indicates, a suffiently clever compiler can warn about either case if it performs additional analysis of what's going to happen during the execution of the program. For some compiler, it helps to enable optimization, since the analysis required to optimize code (without breaking it) can also reveal this kind of potential run-time error.
I'll note that this is an answer to the question you asked: why is there no warning. The answer you accepted is to the implied question: "I want a warning here; how can I enable it?". I'm not complaining, just observing.


text:
Q: What is the difference between "submit" and "deposit"? I am trying to find out the difference between "submit" and "deposit" these words are very confusing when you visit to a bank and somebody ask you "what is the purpose of you to come here and you replied that "I came here to submit money" or "I came here to deposit money" out of these two sentences which is correct and why?

A: To submit something to someone is to offer it for the recipient's approval: you submit a scholarly article to an academic journal, you submit a proposal to a prospective client, you submit your resumé to a prospective employer.
Ordinarily you do not submit your money to a bank; they are eager to have it and are very unlikely to reject it, unless you are a known associate of drug dealers or terrorists.
To deposit something somewhere is literally to put it there, and that is what you do at the bank: you put your money in and eventually (all too soon!) take it out again.

A: You deposit money: give it to the bank for safekeeping and to gain interest.
See collins dictionary here:
deposit
submit


text:
Q: How to insert font awesome icon into text input? How can I insert a calendar web font icon into my input field?

HTML:
<input class="start_date" type="text">

CSS:
.start_date:before {
  font-family: "FontAwesome";
  content: "\f073";
}

A: <input> is a self-closing tag, you cannot have any :before or :after pseudo element in it. You could wrap it into a <label> or <span> so and attach it there.

.start_date:before {
  font-family: "FontAwesome";
  content: "\f073";
}

.start_date:before,
.start_date input {
  vertical-align: middle;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<label class="start_date">
  <input type="text" placeholder="Date">
</label>

Here is an example of having the icon positioned inside the input field.

.start_date {
  position: relative;
}

.start_date:before {
  font-family: "FontAwesome";
  font-size: 14px;
  content: "\f073";
  position: absolute;
  left: 4px;
  top: 50%;
  transform: translateY(-50%);
}

.start_date input {
  text-indent: 18px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<label class="start_date">
  <input type="text" placeholder="Date" />
</label>


text:
Q: Unable to Access Local Host From Docker Container Problem
I have two Docker containers:

*

*a server ran with fastapi;uvicorn

*a client sending a GET request to http://0.0.0.0
The server seems to work just fine as bashing curl -X GET http://0.0.0.0 works as expected. However, my docker client seems unable to get access.
After building the client container (files below), when running docker run -it --name app_client_container app_client:latest I receive the following error:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=80): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: Errno 111 Connection refused'))

Setup
My project looks like this
|- client.Dockerfile
|- client.py
|- client_req.txt
|- server.Dockerfile
|- server.py
|- server_req.txt

Client
# client.Dockerfile
FROM python:3.8

WORKDIR /srv
WORKDIR /srv
ADD client_req.txt /srv/client_req.txt
RUN pip install -r client_req.txt

ADD . /srv
CMD python /srv/client.py

# client.py
import json
import requests
import traceback

try:
    response = requests.get('http://0.0.0.0', timeout=5)
    print(json.dumps(response.json(), indent=4))
except Exception as e:
    print('Connection could not be established :(')
    print('Here is more information:')
    traceback.print_exc()

# client_req.txt
requests

Server
# server.Dockerfile
FROM python:3.8

WORKDIR /srv
ADD server_req.txt /srv/server_req.txt
RUN pip install -r server_req.txt

EXPOSE 80

ADD . /srv
CMD uvicorn server:app --host 0.0.0.0 --port 80 --reload

# server.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

# server_req.txt
fastapi
uvicorn

A: Try running the client with docker run ... --net=host ...
Although the server exposes :80 to the host, the host's network is not, by default, available to other containers; i.e. the host's :80 is not available inside other (including the client) containers.
Alternatively, you may:

*

*reference the host via its DNS within the container;

*create a docker network and bind both containers to it (thereby also using container names to reference)

*or -- somewhat equally to the previous -- use Docker Compose.

A: You can also use default docker bridge network.
Set the IP address to: 172.17.0.1 (for mac it is docker.for.mac.host.internal)
This should work:
response = requests.get('http://172.17.0.1', timeout=5)


text:
Q: Why my recursive code is giving sigsegv error?
Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach to any index with value 0. (Return true or false).

Input: arr = [4,2,3,0,3,1,2], start = 5
Output: true

Explanation: index 5 -> index 4 -> index 1 -> index 3
index 5 -> index 6 -> index 4 -> index 1 -> index 3
Notice that you can not jump outside of the array at any time.

class Solution
{
  public:
    bool canReach(vector<int>& arr, int start)
    {
        if(start<0 || start>=arr.size())
        {
            return false;
        }
        if(arr[start]==0)
        {
            return true;
        }
        bool x = canReach( arr,  start+arr[start]);
        bool y = canReach( arr,  start-arr[start]);
        return (x||y);
    }
};

A: Consider a case where the input vector is arr = {1, 1, 1, 1, 1} and start = 1.According to you code, in this case, there will be an infinite number of recursive calls to the function.
This can be understood as:
if we are at index 1 and do start - arr[i] we reach index 0. Then if we do start + arr[i] we again reach index 1. This leads to an infinite number of calls to the function.
index 1 -> index 0 -> index 1 -> index 0 -> index 1-> so on.
Since recursion uses stack, this may lead to stack-overflow, thus aborting the function execution.
One way to handle this case is to use an unordered_set to store the indecies which have been visited earlier. If we have visited an index earlier than we should simply return false because there is no way that it can return true now.
Here is the implementation you can try:
unordered_set<int> s;
bool canReach(vector<int>& arr, int start) {

    if(start<0 || start>=arr.size() || (s.find(start) != s.end()))
        return false;
    if(arr[start]==0)
        return true;
    s.insert(start);
    bool x = canReach( arr,  start+arr[start]);
    bool y = canReach( arr,  start-arr[start]);
    return (x||y);
}

It should work.


text:
Q: Excel: How to increment time once in every 1000 rows I have a date-time column in DD-MM-YYYY HH:MM:SS format. I need to increment this column value by 10 minutes once in every 1000 rows. Once an increment has been done, the value will remain constant for 1000 rows after which another increment will be made.
I tried to use the standard increment option by using time function, but its available for either time or date but not for both
=TIME(HOUR($L$1),MINUTE($L$1),SECOND($L$1)+INT((ROW()-1/1000)))

I also tried to use MOD function, but it is throwing #VALUE! error on 15-06-2022 01:00:00 cell value
=x1+IF(MOD(ROW()-ROW(A$1),1000)=0,10,0)

Can you please help in this regard

A: Simpler (and more robust than using row() if anybody inserts rows at the top) is:

*

*in A2 put =A1,

*drag down as far as A1000

*in A1001 put =A1+10/60/24

*drag down as far as you need


text:
Q: Assign processors to Hyper V host machine optimally We have a Intel Core i7-3632QM CPU (4 Cores, 8 Threads, 8 Symbols in device manager) on a host machine with Windows 8.
We have a single Hyper V virtual machine with Windows Server 2012.
How do we optimally allocate physical cores/threads for the virtual machine, meaning what should be put into field

Number of virtual processors

And WHY?
I didn't get a thing about vCPU, HT and recommendations from Microsoft, so please don't feed that eyewashed links.. Plain Tech-English would be great!
I want to Dynamically utilize 100% of Host CPU (or perhaps 95% if that's the case/possible), can that be done?
Thanks.

A: The Options of a virtual Machine in Hyper V show in percent how many host resources will be allocated/dedicated to a Guest machine.
So if you have 8 Threads (8 virtual CPUs) on your host, then 8 virtual CPUs in VM's settings means, that Guest will be able to use all 8 Host threads.


text:
Q: Align three figures, Left, Centering, Right with appropriate Captions and Labels? I am learning how to use Latex and currently I am trying to get an understanding of how to place 3 figures all in one line across the page.
Here is my efforts which has sent one figure to the next page and seems to repeat the caption.
% Sample file: math.tex
\documentclass{sample}
\usepackage{xcolor}
\usepackage{setspace}
\usepackage[margin=.7in]{geometry}
\usepackage{parskip}
\setlength{\parindent}{15pt}
\leftskip 0.1in
\parindent -0.1in
\usepackage{graphicx}
\usepackage{mathtools}
\usepackage{enumerate}
\usepackage{verbatim}
\usepackage{fancyvrb}
\usepackage[bottom]{footmisc}
\VerbatimFootnotes

\begin{document}

\begin{figure}[h!]
\centering\includegraphics[scale=.5]{Rachel&Bob}
\caption{Rachel and Bob's basis vectors}\label{Fi:001}
\end{figure}
\begin{figure}[h!]
\includegraphics{Poincare disk model.pdf}
\end{figure}

\end{document}

I got the centering to work on the first figure and the Caption and Label were just fine.
The second figure was sent to the next page and I removed the Caption and Label in order to understand why I had:
"disk.model.pdf"

to the left of the fig which has been placed about two inches to the left of the left hand margin.
Removing both the Caption and Label has had no impact on the text I refer to in the last paragraph.
Any suggestions or pointers where I can research some more on placement of figures.

A: To keep the images and associated captions together, it's best to place the \includegraphics-\caption-\label triplets inside separate minipage environments. For three side-by-side images, I suggest you allocate a width of 0.3\textwidth to each minipage. That way, 0.05\textwidth can be set aside as whitespace between each pair of images. (0.3+0.05+0.3+0.05+0.3=?.)

\documentclass{article} % not 'sample'
\usepackage{xcolor}
\usepackage{setspace}
\usepackage[margin=.7in]{geometry}
\usepackage{parskip}
%\setlength{\parindent}{15pt}
%\leftskip 0.1in
%\parindent -0.1in
\usepackage[demo]{graphicx} % omit 'demo' option in real document
\usepackage{mathtools}
\usepackage{enumerate}
%\usepackage{verbatim}
\usepackage{fancyvrb}
\VerbatimFootnotes
\usepackage[bottom]{footmisc}

\begin{document}
\hrule % just to illustrate width of text block

\begin{figure}[h!]

\begin{minipage}[t]{0.3\textwidth}
\includegraphics[width=\linewidth]{Rachel&Bob}
\caption{Rachel's and Bob's basis vectors} \label{Fi:001}
\end{minipage}
\hfill
\begin{minipage}[t]{0.3\textwidth}
\includegraphics[width=\linewidth]{Poincar\'eDiskModel}
\caption{Poincar\'e disk model} \label{poincare_disk}
\end{minipage}
\hfill
\begin{minipage}[t]{0.3\textwidth}
\includegraphics[width=\linewidth]{SomeOtherImage}
\caption{Some other image} \label{other}
\end{minipage}

\end{figure}

\end{document}


text:
Q: Find a date from a specific list of date I am a beginner in c # and I can not find the solution for my problem.
I am creating a personal project that allows me to send reminders, I have a date list and I need to do tasks between two specific dates in real life.
I found how to get the next date from today's date but I can't find how to get the previous one
Here is my sample code
void calc_x_date()
    {
        List<string> x_dates = new List<string>();
        x_dates.Add("10/01/2017");
        x_dates.Add("14/02/2017");
        x_dates.Add("14/03/2017");
        x_dates.Add("11/04/2017");
        x_dates.Add("09/05/2017");
        x_dates.Add("13/06/2017");
        x_dates.Add("04/07/2017");
        x_dates.Add("08/08/2017");
        x_dates.Add("12/09/2017");
        x_dates.Add("10/10/2017");
        x_dates.Add("14/11/2017");
        x_dates.Add("12/12/2017");

        var allDates = x_dates.Select(DateTime.Parse).OrderBy(d => d).ToList();

        var todayDate = DateTime.Today;
        var nextDate = todayDate >= allDates.Last()
             ? allDates.Last()
             : todayDate <= allDates.First()
                 ? allDates.First()
                 : allDates.First(d => d >= todayDate);

       string NextDate = nextDate.ToString(); // the closest next date from today
       //string PreviousDate =   // the closest previous date from today
    }

Could someone explain me how to find my previous date  please ?
Thanks in advance

A: I'd suggest using List<T>.BinarySearch: that will find the index of the date. If the index is 0 or more, then the exact date was found. If it's negative, then taking ~index will get you the index where the date would have been inserted.
Once you've got that information, it's easy to find the value at the previous index or the next index - but you should consider all the cases of:

*

*Today is before all dates

*Today is after all dates

*Today is a date between the first and last date in the list, but isn't in the list

*Today is equal to the first date

*Today is equal to the last date

*Today is equal to a date in the list which isn't the first or last date

As asides:

*

*I would strongly encourage you to get in the habit of following .NET naming conventions as early as possible

*I'd encourage you not to use strings to represent dates unless you really need to

*If you're doing a lot of date/time work, you may find my Noda Time library easier to use correctly than DateTime

A: Storing dates in string format works. It is however incredibly difficult to do date comparisons. You have to first cast it to numbers, handle the exceptions, etc.
C# has a DateTime object. You can store dates in this and ignore the time. DateTime objects can be compared using the < and > operators.
If you create a class with a start date and an end date, store these objects in a list(of tasks), would that solve your problem? You can also add a text of the task in a string to said object.

A: Here is a Linq approach
List<string> x_dates = new List<string>();
x_dates.Add("10/01/2017");
x_dates.Add("14/02/2017");
x_dates.Add("14/03/2017");
x_dates.Add("11/04/2017");
x_dates.Add("09/05/2017");
x_dates.Add("13/06/2017");
x_dates.Add("04/07/2017");
x_dates.Add("08/08/2017");
x_dates.Add("12/09/2017");
x_dates.Add("10/10/2017");
x_dates.Add("14/11/2017");
x_dates.Add("12/12/2017");

DateTime today = DateTime.Today;
IEnumerable<DateTime> dt_dates = x_dates.Select(DateTime.Parse);

DateTime prev = dt_dates.Where(x => x < today)
                        .OrderByDescending(x => x)
                        .First();

DateTime next = dt_dates.Where(x => x > today)
                        .OrderBy(x => x)
                        .First();

alternative solution
DateTime prev = dt_dates.Where(x => x < today).Max();
DateTime next = dt_dates.Where(x => x > today).Min();


text:
Q: Error: module 'pandas' has no attribute 'read_pdf' When importing the read_pdf method from pandas using
import pandas as pd

as the example demonstrated
It shows the following error message
AttributeError: AttributeError: module 'pandas' has no attribute 'read_pdf'
Environment
python --version: python 3.8.8
OS and it's version: ? windows 10
Anaconda (version 1.7.2)

I was trying to read files that are of type .pdf / .docx / .txt from a file system that is already there.

Example code:
import pandas as pd
import os # Os moduel for Operating System opertions
import mimetypes

# To change the current working directory to a new directory we use
# os.chdir("Directory path")
os.chdir("C:\\Users\\adity\\Documents\\Parent")

# To List the files and folders in the current working directory
# Return the file in form of List
fid = os.listdir() #filesInDirectory

# To check whether child 1 2 3 exist or not
def checkChild(d):
    if len(d) == 0:
        return False
    if 'Child1' in d and 'Child2' in d and 'Child3' in d:
        return True
    else:
        return False

# dc1 Directory Child One; dof Dictionary File System
# nof name of file , ext Extension

if checkChild(fid) == True: # if folders are there than read respective files
    for folder in fid:
        fileDir = folder
        os.chdir(directory+f"\\{fileDir}") # Changing directory to respective child
        dc = os.listdir()[0] # dc contains the name of file with extension
        nof,ext = os.path.splitext(dc)
        if ext =='':
            ext = mimetypes.guess_extension(os.getcwd())

        if ext == '.pdf' and fileDir == 'Child1':
            child1Pdf = pd.read_pdf(f'{dc}')  #**Error Line**

Error Output:

*AttributeError                            Traceback (most recent call last)  in
9         print(dc)
10         if ext == '.pdf' and fileDir == 'Child1':
---> 11             child1Pdf = pd.read_pdf(f'{dc}')
12
13
~\anaconda3\lib\site-packages\pandas_init_.py in getattr(name)
242         return _SparseArray
243
--> 244     raise AttributeError(f"module 'pandas' has no attribute '{name}'")
245
246
AttributeError: module 'pandas' has no attribute 'read_pdf'*

I am not getting any solution for this error

A: If you're importing pdf data as tabular data
import tabula
import pandas as pd

#declare the path of your file
file_path = "/path/to/pdf_file/data.pdf

#Convert your file
df = tabula.read_pdf(file_path)

A: If its just about reading a PDF as pandas dataframe then have a look here, the answer clearly shows how you can read pdf as pandas dataframe using tabula
import tabula

df = tabula.read_pdf(
    "https://github.com/chezou/tabula-py/raw/master/tests/resources/data.pdf")

df_0 = df[0]

print("type of df :", type(df))
print("type of df_0", type(df_0))

Output
type of df : <class 'list'>
type of df_0 <class 'pandas.core.frame.DataFrame'>

My bad I just explored the actual package tabula in python and realized there is no read_pdf there, so after digging into this and reproducing the issue my final experiment yields foolowing results

*

*Use tabula-io to use the function read_pdf

*to install run command pip install tabula-py

Use the following code sample
from tabula.io import read_pdf
df = read_pdf("https://github.com/chezou/tabula-py/raw/master/tests/resources/data.pdf")
df_0 = df[0]
print("type of df :", type(df))

Output


text:
Q: Deformation of extensions I am trying to work on a deformation theory problem, but I don't have much experience in it, so any reference or insight would be much appreciated.
Given two coherent sheaves $F$ and $G$ on a projective variety $X$, we can consider an extension $E$ of these two sheaves $0\to F \to E \to G \to 0$. Assume we have two deformations $F'\to F$ and $G' \to G$ (here I am treating deformations as in Hartshorne's book Deformation Theory). I was wondering if there is a way to induce a deformation of $E$ in a "natural" way. For example, if there exists a extension in $Ext^1_{X'}(G',F')$ compatible with the deformation maps, essentially, saying that there exists a surjective map  $Ext^1_{X'}(G',F')\to Ext^1_{X}(G,F)\to 0$.
The above result is general in some sense, and I didn't find any reference in this direction. I was trying to apply this in the particular case where $F$ and $G$ are ideal sheaves of points in the $\mathbb{C}$-projective space $\mathbb{P}^3$, and we can even assume that the deformation $G$ is the trivial one, like $G'$ is just the pullback of $G$.
Thanks.


text:
Q: How to build and wire Spring database dependency .JAR project for use with multiple .WAR projects? I am building a suite of web services that all access the same database but using different credentials. So to modularize the database code I am moving it out of each web app .WAR files and giving the database calls its own .JAR file. So that if WebApp1 and WebApp2 use a getAllColumnsFromTable1 MyBatis call I don't have to define the same mapper and domain object in both projects.  That way I only have to change the MyBatis code in one place if Table1 ever changes, and less copy and paste mistakes.
WebApp1 applicationContext.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

  <context:annotation-config />

  <context:component-scan base-package="com.example.webapp1.service" />
  <context:component-scan base-package="com.example.webapp1.controller" />

  <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:/example/ds/WebApp1DS" />
  </bean>

  <bean id="databaseConnector" class="com.example.databaseconnector.connector"
    <property name="dataSource" ref="dataSource" />
  </bean>
</beans>

So what I want to pass to the database connector .JAR file is just the data source that the .WAR is using.
WebApp1 pom.xml :
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>WebApp1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>3.2.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>3.2.3.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>com.example</groupId>
      <artifactId>databaseconnector</artifactId>
      <version>0.0.1-SNAPSHOT</version>
    </dependency>
  </dependencies>
</project>

Then have something like this in one of the services in the .WAR
WebApp1 Service.java:
package com.example.webapp1.service;

import com.example.databaseconnector.domain.TableSearchResult;
import com.example.databaseconnector.persistence.TableMapper;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class Service {
  @Autowired
  private TableMapper tableMapper;

  public List<TableSearchResult> getSearchResults(String param) {
    return tableMapper.getAllColumnsFromTable1(param);
  }
}

Then on the .JAR side I have
databaseconnector pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>databaseconnector</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>Database Connector</name>

  <dependencies>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.2.3</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.1</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.0.0.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.0.0.RELEASE</version>
    </dependency>
  </dependencies>
</project>

databaseconnector DatabaseConnection.java:
package com.example.databaseconnector.connector;

import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

public class DatabaseConnection implements InitializingBean {
  private DataSource dataSource;
  private DataSourceTransactionManager dataSourceTransactionManager;
  private SqlSessionFactoryBean sqlSessionFactoryBean;
  private MapperScannerConfigurer mapperScannerConfigurer;

  public DataSource getDataSource() {
    return this.dataSource;
  }

  public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
  }

  @Override
  public void afterPropertiesSet() throws Exception {
    if (getDataSource() == null) {
      throw new IllegalArgumentException("Property 'dataSource' is required");
    } else {
      this.configureDataSourceTransactionManager();
      this.configureSqlSessionFactoryBean();
      this.configureMapperScannerConfigurer();
    }
  }

  private void configureDataSourceTransactionManager() {
    this.dataSourceTransactionManager = new DataSourceTransactionManager();

    this.dataSourceTransactionManager.setDataSource(dataSource);
  }

  private void configureSqlSessionFactoryBean() {
    this.sqlSessionFactoryBean = new SqlSessionFactoryBean();

    this.sqlSessionFactoryBean.setDataSource(dataSource);

    this.sqlSessionFactoryBean.setConfigLocation(
        new ClassPathResource("mybatis-config.xml"));

    this.sqlSessionFactoryBean.setTypeAliasesPackage(
        "com.example.sewp5databaseconnector.domain");
  }

  private void configureMapperScannerConfigurer() {
    this.mapperScannerConfigurer = new MapperScannerConfigurer();

    this.mapperScannerConfigurer.setBasePackage(
        "com.example.databaseconnector.persistence");

    this.mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
  }
}

When I run WebApp1 the program fails because it could not find the TableMapper bean to autowire the mapper in the service. What Spring setup am I missing to get this to all work together, or am I going about this the completely wrong way?

A: You seem to be missing your Spring configuration for the TableMapper bean. That class need to be a Spring bean in order for it to be injected into Service.
Add the relevant bean configuration to your applicationContext.xml

A: Spring context hierarchy can help in common code scenario.
If you have multiple webapps in a single EAR, EAR can have its own context, which is the parent of the individual webapp contexts.
Also in each webapp, you can have one root context and individual children context as well.
You can define this hierarchy in web.xml. Parent context can be specified through context parameters: locatorFactorySelector and parentContextKey. Root context through context parameter contextConfigLocation(outside servlet). Child context can be specified in the init param - context parameter of each of the servlet.
Have one jar in EAR holding all your common service and DAO layer code and define them in beanRefContext.xml(which is basically another application context xml). make this jar available in classpath.
In web.xml of each app where you want to refer parent context code:
    <!--  root application context -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:rootContextBeans.xml</param-value>
    </context-param>
    <!--  shared service layer - parent application context -->
    <context-param>
        <param-name>locatorFactorySelector</param-name>
        <param-value>classpath:beanRefContext.xml</param-value>
    </context-param>
    <context-param>
        <param-name>parentContextKey</param-name>
        <param-value>servicelayer-context</param-value>
    </context-param>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcherServletApp1</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:webApp1.xml</param-value>
        </init-param>
    </servlet>

where beanRefContext.xml will be like:
    <beans>
      <bean id="servicelayer-context" class="org.springframework.context.support.ClassPathXmlApplicationContext">
        <constructor-arg>
          <list>
            <value>data-layer-context.xml</value>
          </list>
        </constructor-arg>
      </bean>
    </beans>

This way you will achieve what you want.


text:
Q: Assign labels based on given examples for a large dataset effectively I have matrix X (100000 X 10) and vector Y (100000 X 1). X rows are categorical and assume values 1 to 5, and labels are categorical too (11 to 20);
The rows of X are repetitive and there are only ~25% of unique rows, I want Y to have statistical mode of all the labels for a particular unique row.
And then there comes another dataset P (90000 X 10),  I want to predict labels Q based on the previous exercise.
What I tried is finding unique rows of X using unique in MATLAB, and then assign statistical mode of each of these labels for the unique rows. For P, I can use ismember and carry out the same.
The issue is in the size of the dataset and it takes an 1.5-2 hours to complete the process. Is there a vectorize version possible in MATLAB?
Here is my code:
[X_unique,~,ic] = unique(X,'rows','stable');
labels=zeros(length(X_unique),1);
for i=1:length(X_unique)
    labels(i)=mode(Y(ic==i));
end

Q=zeros(length(P),1);
for j=1:length(X_unique)
    Q(all(repmat(X_unique(j,:),length(P),1)==P,2))=label(j);
end

A: You will be able to accelerate your first loop a great deal if you replace it entirely with:
labels = accumarray(ic, Y, [], @(y) mode(y));

The second loop can be accelerated by using all(bsxfun(@eq, X_unique(i,:), P), 2) inside Q(...). This is a good vectorized approach assuming your arrays are not extremely large w.r.t. the available memory on your machine. In addition, to save more time, you could use the unique trick you did with X on P, run all the comparisons on a much smaller array:
[P_unique, ~, IC_P] = unique(P, 'rows', 'stable');

EDIT:
to compute Q_unique in the following way: and then convert it back to the full array using:
Q_unique = zeros(length(P_unique),1);
for i = 1:length(X_unique)
    Q_unique(all(bsxfun(@eq, X_unique(i,:), P_unique), 2)) = labels(i)
end

and convert back to Q_full to match the original P input:
Q_full = Q_unique(IC_P);

END EDIT
Finally, if memory is an issue, in addition to everything above, you might want you use a semi-vectorized approach inside your second loop:
for i = 1:length(X_unique)
    idx = true(length(P), 1);
    for j = 1:size(X_unique,2)
        idx = idx & (X_unique(i,j) == P(:,j));
    end
    Q(idx) = labels(i);
%    Q(all(bsxfun(@eq, X_unique(i,:), P), 2)) = labels(i);
end

This would take about x3 longer compared with bsxfun but if memory is limited then you gotta pay with speed.
ANOTHER EDIT
Depending on your version of Matlab, you could also use containers.Map to your advantage by mapping textual representations of the numeric sequences to the calculated labels. See example below.
% find unique members of X to work with a smaller array
[X_unique, ~, IC_X] = unique(X, 'rows', 'stable');
% compute labels
labels = accumarray(IC_X, Y, [], @(y) mode(y));
% convert X to cellstr -- textual representation of the number sequence
X_cellstr = cellstr(char(X_unique+48)); % 48 is ASCII for 0
% map each X to its label
X_map = containers.Map(X_cellstr, labels);
% find unique members of P to work with a smaller array
[P_unique, ~, IC_P] = unique(P, 'rows', 'stable');
% convert P to cellstr -- textual representation of the number sequence
P_cellstr = cellstr(char(P_unique+48)); % 48 is ASCII for 0
% --- EDIT --- avoiding error on missing keys in X_map --------------------
% find which P's exist in map
isInMapP = X_map.isKey(P_cellstr);
% pre-allocate Q_unique to the size of P_unique (can be any value you want)
Q_unique = nan(size(P_cellstr)); % NaN is safe to use since not a label
% find the labels for each P_unique that exists in X_map
Q_unique(isInMapP) = cell2mat(X_map.values(P_cellstr(isInMapP)));
% --- END EDIT ------------------------------------------------------------
% convert back to full Q array to match original P
Q_full = Q_unique(IC_P);

This takes about 15 seconds to run on my laptop. Most of which is consumed by computation of mode.


text:
Q: Can Syntax Errors be handled? Consider the following code:
try:
    if True a = 1  #It's missing a colon So it's a SyntaxError!!!!!!!
except SyntaxError:
    print 'hey'

You'd expect it to print hey However It raises a SyntaxError, The same error I'm trying to avoid. So Can all Exceptions be handled using a try-except block? Well If SyntaxError's were an exception why is it included in the built-in exceptions? and finally how can I fix the above piece of code so that it handles the exception properly?
Note: I know what I'm trying to do Is utterly pointless and serves no real purpose

A: Of course you need SyntaxError as a built-in exception - what else should be raised if the compiler/parser encounters a syntax error?
You're right that this error usually happens at compile time, which is before you're able to catch it (runtime). (And how would you recover from it?)
I can think of one exception, though:
>>> try:
...    eval("hello =")
... except SyntaxError:
...    print("Hey! Who's using eval() anyway??")
...
Hey! Who's using eval() anyway??

A: SyntaxError is a perfectly ordinary built-in exception. It is not special in any way. Only the circumstances of when it's (usually) thrown are a bit unusual.
A syntax error means that the code featuring said error cannot be parsed. It doesn't even begin to be a valid program, hence it cannot be executed. Therefore SyntaxError exceptions are raised before the program is run, and hence can't be caught from within the program.
More specifically, this exception is raised by the parser. Because the parser runs fully before the code is executed, rather then interleaved with it, a program can't catch its own syntax errors.
The parser itself is just another program though: Code invoking the parser can catch SyntaxErrors like every other exception (because it is like every other exception). Examples of "invoking the parser" include:

*

*compile, exec, eval

*import statements

*Several functions in modules like ast, tokenizer, parser, etc.


text:
Q: Using AWS Amplify Auth on the server with custom auth-storage I have a server side rendered react application, that invokes Amplify's Auth.CurrentAuthenticatedUser method to check for auth before displaying protected pages.
On the client side I'm using cookieStorage. It works perfectly fine as the credentials are retrieved successfully when invoking Auth.CurrentAuthenticatedUser upon accessing protected routes via react-router's BrowserRouter.
On the server-side (when the protected routes are accessed by a direct http call), I'm using the following configuration for Amplify:
import cookie from 'cookie';

class ServerCookieStorage {
  constructor(requestCookie) {
    this.cookieObj = {};
    if (requestCookie) this.cookieObj = cookie.parse(requestCookie);
  }
  setItem(key, value) {
    this.cookieObj[key] = value;
  }
  getItem(key) {
    return this.cookieObj[key];
  }
  removeItem(key) {
    this.cookieObj[key] = '';
  }
}

Amplify.configure({
  Auth: {
    identityPoolId: 'placeholder',
      region: 'placeholder',
      userPoolId: 'placeholder',
      userPoolWebClientId: 'placeholder',
      storage: new ServerCookieStorage(event.headers.Cookie);
      //cookie header in aws lambda functions is located in event.header.Cookie
  }
});

I've logged what goes into the setItem and getItem methods and it seems to be retrieving all the information fine when the Auth.CurrentAuthenticatedUser method is invoked, however the method is failing with the error Not Authenticated.
Am I missing something here?

A: I realised that the Auth.CurrentAuthenticatedUser uses the fetch method under the hood, which is why it was failing. The solution was to provide a fetch method polyfill for node using node-fetch, I did it like so:
const fetch = require('node-fetch');
global.fetch = fetch;


text:
Q: PHP/Python json_decode doesn´t display special characters like € I got a json which is generated in a python program and looks like this:
{"0": {"ausschreiber": "Beispiel; Zeitarbeit GmbH", "beschreibung": "\r\nF\u00fcr unseren Kunden suchen wir motivierte studentische Aushilfen auf flexibler Stundenbasis (450\u0080-Basis)", "datum": "17.11.2016", "name": "Studentische Hilfskr\u00e4fte gesucht", "email": "info@hindi.de"}}

now i am decoding the json in my php program to get an associative array and display this on the website.
The Problem is that the special characters like the € char are not displayed but special chars like ö ä ü are displayed.
Here is the php program:
<?php
header('Content-Type: text/html; charset=utf-8');

function compare($old_data, $new_data){
    $old_result = json_decode($old_data, true);
    $new_result = json_decode($new_data, true);
    echo $new_result[0]['beschreibung'];
}

function go4it(){
    $db_data=json_content(); //creates the json from the Database
    $crawler_data = file_get_contents('http://localhost/phppath/python_program.cgi'); //calls the cgi which returns the json
    compare($db_data, $crawler_data);
}
go4it();

What i tried:

*

*set the header to utf-8

*$new_result = json_decode(utf8_encode($new data), true);

*iconv_set_encoding("internal_encoding", "UTF-8");

*iconv_set_encoding("input_encoding", "UTF-8");

*iconv_set_encoding("output_encoding", "UTF-8");
Thanks for your help!
EDIT 1
so it seems like the issue is located in the python program, thanks to @FranzGleichmann . I think the problem is with the encoding of the page where i get the content from. The page says it is ISO-8859-1 so i tried this:
url = 'https://www.example.com'
source_code = requests.get(url)
plain_text = source_code.text
plain_text.decode('iso-8859-1', 'ignore').encode('utf8', 'ignore')
print(plain_text.encoding)

but then i get the error: "UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 8496: ordinal not in range(128)"

A: it was a problem with the python script


text:
Q: J2ME LWUIT - Error showing outside screen labels on scroll I'm working on a J2ME application using LWUIT.
I need to show 10 values with a Label each one.
Something like this:
Label1       Value1
Label2       Value2
Label3       Value3
Label4       Value4
............
LabelN       ValueN

I'm using 1 Container for each "row" and one big Container for each "row container"
My problem is with the "rows" outside the screen. The last 4 pairs of Label+value are not showing when I use the scroll
I don't know why.
Can someone solve this?
This is my code:
this.setLayout(new BorderLayout());
PromotionMonitorDTO promotionMonitorDTO = Cloud.getPromotionMonitor();
Utils utils = new Utils();
Font f = Font.getBitmapFont("movSmall");
Container cellContainer = new Container(new BoxLayout(BoxLayout.Y_AXIS));
Container rowContainer = new Container(new BoxLayout(BoxLayout.X_AXIS));

//FIRST PAIR///////////////////////

String stringValue = utils.calendarToShorString(promotionMonitorDTO.getLastUpdate());
Label valor = new Label(LanguageManager.getText("LastUpdate"));
valor.getStyle().setFont(f);
rowContainer.addComponent(valor);
valor = new Label(LanguageManager.getText(stringValue));
valor.getStyle().setFont(f);
rowContainer.addComponent(valor);
cellContainer.addComponent(rowContainer);
rowContainer = new Container(new BoxLayout(BoxLayout.X_AXIS));

//SECOND PAIR///////////////////////

stringValue = String.valueOf(promotionMonitorDTO.getInitialTarget());
valor = new Label(LanguageManager.getText("InitialTarget"));
valor.getStyle().setFont(f);
rowContainer.addComponent(valor);
valor = new Label(LanguageManager.getText(stringValue));
valor.getStyle().setFont(f);
rowContainer.addComponent(valor);
cellContainer.addComponent(rowContainer);

////////8 MORE PAIRS////////////////////

this.addComponent(BorderLayout.NORTH, cellContainer);

A: Finally I solved.
I removed the second Container, I changed the Layout of the form to BoxLayout(BoxLayout.Y_AXIS) and I added all the "row containers" to the form,
With those changes, I have the same Graphic funcionality and the scroll is working.
I have to remove the question? o leave it for others?

A: Maybe you must "freeze" the Form and make it not scrollable. Set the Form not scrollable using Form.setScrollable(false) and make the center/north Container of your BorderLayoutscrollable. Try to do that.


text:
Q: bundle.js not found. React, Node, Webpack I have generated bundle.js file but it is not available when I run server.
Same thing is for style.css.
Probably error is small but I can't find it.
build
NODE_ENV='production' webpack -p

start
NODE_ENV=production NODE_PATH=./src node  server.js

server.js
require('babel-core/register');
['.css', '.less', '.sass', '.ttf', '.woff', '.woff2'].forEach((ext) => require.extensions[ext] = () => {});
require('babel-polyfill');
require('server.js');

webpack.config.js
global.Promise         = require('bluebird');

const webpack            = require('webpack');
const path               = require('path');
const ExtractTextPlugin  = require('extract-text-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

const publicPath         = './public';
const cssName            = 'styles.css';
const jsName             = 'bundle.js';

const plugins = [
  new webpack.DefinePlugin({
    'process.env': {
      BROWSER:  JSON.stringify(true),
      NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development')
    }
  }),
  new ExtractTextPlugin(cssName)
];

if (process.env.NODE_ENV === 'production') {
  plugins.push(
    new CleanWebpackPlugin([ './public/' ], {
      root: __dirname,
      verbose: true,
      dry: false
    })
  );
  plugins.push(new webpack.optimize.DedupePlugin());
  plugins.push(new webpack.optimize.OccurenceOrderPlugin());
}

module.exports = {
  entry: ['babel-polyfill', './src/client.js'],
  debug: process.env.NODE_ENV !== 'production',
  resolve: {
    root:               path.join(__dirname, 'src'),
    modulesDirectories: [ 'node_modules' ],
    extensions:         ['', '.js', '.jsx']
  },
  plugins,
  output: {
    path: `${__dirname}/public/`,
    filename: jsName,
    publicPath
  },
  module: {
    loaders: [
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style-loader', 'css-loader!postcss-loader')
      },
      {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract('style-loader', 'css-loader!postcss-loader!less-loader')
      },
      { test: /\.gif$/, loader: 'url-loader?limit=10000&mimetype=image/gif' },
      { test: /\.jpg$/, loader: 'url-loader?limit=10000&mimetype=image/jpg' },
      { test: /\.png$/, loader: 'url-loader?limit=10000&mimetype=image/png' },
      { test: /\.svg/, loader: 'url-loader?limit=26000&mimetype=image/svg+xml' },
      { test: /\.(woff|woff2|ttf|eot)/, loader: 'url-loader?limit=1' },
      { test: /\.jsx?$/, loader: process.env.NODE_ENV !== 'production' ? 'react-hot!babel!eslint-loader' : 'babel', exclude: /node_modules/ },
      { test: /\.json$/, loader: 'json-loader' }
    ]
  },
  eslint: {
    configFile: '.eslintrc'
  },
  devtool: process.env.NODE_ENV !== 'production' ? 'source-map' : null,
  devServer: {
    headers: { 'Access-Control-Allow-Origin': '*' }
  }
};

src/server.js
...
const assetUrl = process.env.NODE_ENV !== 'production' ? 'http://localhost:8050' : '';
function renderHTML(componentHTML, initialState) {
  return `
    <!DOCTYPE html>

          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>Hello React</title>
          <link rel="stylesheet" href="${assetUrl}/public/styles.css">

${componentHTML}

  `;
}
...

any guesses?

A: In your file you have given the src of the css and bundle.js file to start with http://localhost:8050, but src is always given with relative to the file you are in
you should use
<link rel="stylesheet" href="../public/styles.css">

and

The path comes from the assumption that public directory is directly outside the src directory.


text:
Q: Universal algorithm for generating properities I need to make algorithm, what take random unique string (hash, whatever) and generate multiple random properities from prepaired lists.
Example: [cat algorithm]
color: white,black,brown
eye-color: blue, green, brown
size: 10,20,30

function algorithm(random_unique_hash){
   ...magic...
   return [color, eye-color, size]
}

Returned cat is absolutely unique to her string.
String is unique in whole list of strings.
Every cat must be different.
I need to be able to make hash again from properities.
Is this possible? Or it needs to work in different way? Did I need to make cat and then make unique checksum?
Where to start?

A: You've got three colors, three eye-colors, and three sizes. That means there are exactly 3*3*3=27 different cats you can make. So the random_unique_hash should just be a number from 0 to 26.
To get the properties from the hash, break the hash down into indexes using division and the modulo operator, e.g.
index1 = random_unique_hash % 3
index2 = (random_unique_hash / 3) % 3
index3 = random_unique_hash / 9

The indexes can then be used to access the correct entry in each property list.
To get the hash from the properties you'll need to find the index of the property. Then combine all of the indexes to recreate the hash, like this
random_unique_hash = index3 * 9 + index2 * 3 + index1


text:
Q: How do you change background of specific cell in a JQuery.DataTable? I'm trying to change the styling of some specific cells in a DattaTable, but I'm not sure how to do that. I know how to change for an entire column, but that's not what i need.
So let's say that my data is like:
{
name: "user1",
gender : "f",
age: 54
},{
name: "user1",
gender : "m",
age: 33
}

In my table, I have
columns: [{
data: "name"
},{
data: "age"
}]

And I want to highlight, lets say, the age cells in blue case gender = "m" or red case gender = "f".
Any suggestion on how I can accomplish that?
Thank you!

A: You would use the column configuration's createdCell function.
Basically, you need to add a column definition for the gender column that includes a callback that will be called when the cell is populated.  Try adding this object to your columns array:
    {
      data: "gender",
      createdCell: function(td, cellData, rowData, row, col){
        var color = (cellData === 'm') ? 'blue' : 'red';
        $(td).css('color', color);
      }
    }

Here is a working example.


text:
Q: How can I hide/encrypt my files from another user using the same server I am connecting to my server provided by institution via ssh. It is an Ubuntu server.
Home folder contains many users.  Each user has a password. But I am not sure whether any user can enter into my folder.
I want to either hide or encrypt my folder. What I need to execute on my terminal?

A: As others have pointed out, you can't stop system administrators (anyone with sudo access) accessing your files.  Even if you encrypt them, if you need to access their content on the server, then an admin can snoop on you while you do.  This is true in most/all operating systems.
Your home directory is readable by all other users, usually by default.  In comments you said your home directory had read permissions by all users.
Often all you need to do to stop other regular users is change the permissions on your home directory;
chmod 700 ~

This will block all users except for root (admin) from your home directory.
If you need to encrypt your data for legal or commercial reasons then this is often not enough unless you have been informed that the drives are encrypted.

A: reading the title "hide/encrypt my files " ...
To encrypt a file (in the example below, denoted F);
(e.g with openssl,
using AES with CBC as Mode Of Operation)
AES - Advanced Encryption Standard
CBC - Cipher Block Chaining
openssl aes-256-cbc -base64 -pbkdf2 -in F

Note: pbkdf2 and -iter is not supported by lower versions than OpenSSL 1.1.1
One could use -iter <integer> to add a extra layer of security.
This, makes it harder(by making it slower) to try to brute force(guess) the password, but if a ridiculous amount of iterations is used, it will take very long - although, this is symmetric encryption and that is quite fast most of the time, just thought of mentioning this.
Note: use >= 10000 iterations
openssl aes-256-cbc -base64 -pbkdf2 -iter 10000 -in F

Decrypt
Denoting encrypted file "file.enc":
cat file.enc | openssl aes-256-cbc -base64 -pbkdf2 -d

Encrypt multiple files
(With the same extension) instead of encrypting every file:
For example,
to encrypt all files ending with .odt, in the folder odtFiles with a unique password (which is asked for interactively)
and output the encrypted files to <originalfilename>.enc:
find odtFiles/ -name "*.odt" -type f -exec openssl aes-256-cbc -base64 -pbkdf2 -in {} -out {}.enc \;

References:
Related OpenSSL 1.1.1b warning: Using -iter or -pbkdf2..
OpenSSL Manual


text:
Q: Is there a way to customize the Android Ringtone Picker Dialog? I show a dialog for selecting one of the native ring tones / text tones with the following code:
private void showTonePicker(int toneType, String pickerTitle) {
[...]

Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
    intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, toneType);
    intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, pickerTitle);
    intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
    intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, userTone.equals(TFSettings.SILENT_TONE_ID) ? null : Uri.parse(userTone));
    startActivityForResult(intent, (toneType == RingtoneManager.TYPE_RINGTONE ? 1 : 2));
}

I call the above method like this:

*

*for selecting text tone:
showTonePicker(RingtoneManager.TYPE_NOTIFICATION, getString(R.string.texting_tone));

*for selecting ring tone:
showTonePicker(RingtoneManager.TYPE_RINGTONE, getString(R.string.ringing_tone));

I have two problems to solve:

*

*I must show lower cased buttons

*In both cases (i.e. when selecting ring tone and also when selecting text tone), the native dialof shows "Default ringtone". I must display "Default text tone" in case of selecting a text tone (in this case toneType = RingtoneManager.TYPE_NOTIFICATION).
Is there a way to resolve these? Can we customize the native tone picker?
Thanks for the answers in advance!
Regards.

A: To set default ringtone, you have to set EXTRA_RINGTONE_EXISTING_URI first.
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, ringtoneUri);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, ringtoneUri);

A:
Can we customize the native tone picker?

No, sorry, not with respect to the items that you describe. You would need to build your own UI for this.

A: I'm not sure it's possible. Besides, there is no guarantee the RingtonePreference is going to open the System's ringtone picker. The user might have another app installed that has an activity with the android.intent.action.RINGTONE_PICKER intent filter declared in the manifest and he might even have it as the default Ringtone picker.
You might implement a custom RingtonePreference and a custom RingtonePickerActivity and force your custom Ringtone picker to be open but you might irritate your users.
If I may ask, for what reason would you like to change it anyway?