text:
Q: Switching from one control (textbox) to another makes disabled text box to be enabled WPF By pressing enter I am moving from one control to another, all of my controls are located in Grid, here is an image of that:

and what is issue here, in case some of my controls are disabled, when I "jump" to that control it's becoming enabled, and if one of my controls is button, its being fired like its mouse clicked.
I dont know how to solve this,
this is how It looks right (my code) now and how I tried to solve this (To keep control disabled when I jumpt on it).
Here is my xaml 3 textboxes, and 3 comboboxes
<TextBox Name="txt1"   Grid.Row="0"  Grid.Column="1"         Margin="0,0,10,0" FontSize="15"  VerticalContentAlignment="Center" />
<TextBox Name="txt2"   Grid.Row="1"  Grid.Column="1"         Margin="0,5,10,0" FontSize="15" VerticalContentAlignment="Center"/>
<TextBox Name="txt2"   Grid.Row="2"  TextWrapping="Wrap"     Grid.Column="1" Margin="0,5,10,0" FontSize="15"  />
<ComboBox Name="cmb1"  Grid.Row="3"  Grid.Column="1"         FontSize="15" Margin="0,5,10,0" />
<ComboBox Name="cmb2"  Grid.Row="4"  Grid.Column="1"         FontSize="15" Margin="0,5,10,0"  />
<ComboBox Name="cmb3"  Grid.Row="5"  Grid.Column="1"         FontSize="15" Margin="0,5,10,0" />

<Grid Grid.Row="6" Grid.Column="1" Margin="0,5,10,0">
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="85*"/>
    <ColumnDefinition Width="15*"/>
</Grid.ColumnDefinitions>
<ComboBox Name="cmb4" Grid.Column="0" IsEnabled="False" FontSize="15" >
    <ComboBox.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="#E0E4E5" />
    </ComboBox.Resources>
</ComboBox>

<Button x:Name="btnUnlockcmb4"
                Grid.Column="5"
                FontSize="15"
                BorderThickness="1.5"
                HorizontalContentAlignment="Center"
                VerticalContentAlignment="Center"
                Margin="4,0,0,0"
                Foreground="White"
                Background="White"
                BorderBrush="#0091EA"  Click="btnUnlockcmb4_Click">
                    <Button.Template>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border BorderThickness="{TemplateBinding BorderThickness}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            Background="{TemplateBinding Background}">
                                <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                            </Border>
                        </ControlTemplate>
                    </Button.Template>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>
                        <Image Source="/Icons/unclock.png" Margin="4" Grid.Column="0" Width="Auto"/>
                        </Grid>
                </Button>
            </Grid>

Acctually that are controls that i am "jumping from one to another".
And cmb4 should stay disabled, just jump it away but dont change his state..
Here is my code:
private void Grid_PreviewKeyDown_1(object sender, KeyEventArgs e)
    {
        try
        {
            if (e.Key == Key.Enter)
            {

                UIElement element = e.Source as UIElement;

                //check is enabled = false as it is, so keep it disabled
                if (element.IsEnabled == false)
                {
                    element.IsEnabled = false;
                }
                else
                {
                    element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

NOTICE BUTTON btnUnlockcm4, which is ussualy setting IsEnabled property to True on my cmb4, so by pressing enter is being fired I guess that is reason why it is enabling my cmb4?
EDIT:
Grid which holds controls:
<Grid Grid.Row="1" Grid.Column="0" Margin="0,3" PreviewKeyDown="Grid_PreviewKeyDown_1">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="25*"/>
                    <ColumnDefinition Width="75*"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="45" />
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="70"/>
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="45"/>
                    <RowDefinition Height="45" />
                    <RowDefinition Height="45"/>
                    <RowDefinition MinHeight="150"/>
                    <RowDefinition Height="45" />
                </Grid.RowDefinitions>

A: Try to set the IsTabStop property of the Button to false:
<Button x:Name="btnUnlockcmb4"
         IsTabStop="False"
         Grid.Column="5"
         FontSize="15"
         ...


text:
Q: How to display the console output in a text area with sepertid calsses in javax.swing.JFrame I'm trying to display the console output in a text area.
I have a (view) bottom that creates object from class Functional. Inside this class there is method that view all the context of table in table in data base and return the result of the query and printed it into the console window. So I need to display this output from the console window to a text area in the GUI class .
This is the GUI class:
public class MainGUI extends javax.swing.JFrame {
    private void SearchButtonActionPerformed(java.awt.event.ActionEvent evt) {
        Functional search = new Functional();
        search.search(SearchTextField.getText(), ItemsComboBox.getSelectedItem().toString());

    }
}

This is the Functional class:
public class Functional {

    public void viewDtailes(String item) {

        try (Connection con = DriverManager.getConnection("jdbc:odbc:Library_DNS");
             Statement stmt = con.createStatement()) {
            if(item.equals("magazins")){
                String sql = "SELECT * FROM " + item;
                ResultSet rs = stmt.executeQuery(sql);
                while(rs.next()){
                    System.out.println(" callNo : " + rs.getString("callno") + " title: " + rs.getString("title")+" Vnom :" + rs.getString("Vnom") + " status: " + rs.getBoolean("status"));
                }
            } else {
                String sql = "SELECT * FROM "+ item;
                ResultSet rs = stmt.executeQuery(sql);
                while(rs.next()){
                    System.out.println("callNo : " + rs.getString("callno")+ " title: " + rs.getString("title")+ " author :" + rs.getString("author") + " status: " + rs.getBoolean("status"));
                }
            }
        } catch (SQLException sqle) {
            System.out.println("Sql Exception :" +sqle.getMessage());
        }
    }
}

The output from console:

I need to display the console output in this text area GUI:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Type error in explicitly typed binding - Haskell I've been struggling for like an hour to understand some things in higher order functions and now I am at the point that I cannot move any further because of this error:
    hof :: [Integer] -> (Integer -> Integer)
    isIn :: [Integer] -> Integer -> Integer
    isIn [] s = 0
    isIn [] _ = 0
    isIn (h:t) s
        | h == s = 0 {-<-------- error points here here-}
        | otherwise = isIn(t) + 1
    hof s = \n -> isIn s n

      ERROR file:.\Lab2.hs:111 - Type error in explicitly typed binding
      *** Term           : isIn
      *** Type           : [Integer] -> Integer -> Integer -> Integer
      *** Does not match : [Integer] -> Integer -> Integer

A: You are missing the second argument in the recursive call to isIn; it should be
 | otherwise = isIn t s + 1
 --                   ^

While not an error, you also have a redundant base case; s and _ are both irrefutable patterns, so just isIn [] _ = 0 is sufficient.
Also not an error, but there is no difference between hof and isIn, as you can eta-reduce the definition to
hof s = isIn s

and again to
hof = isIn


text:
Q: React Native Android release apk crashed on splash screen with 0.63.2 after updating streamchat version I have created my application in React Native
When I install debug apk or run application from android studio then its working fine but when i generate release apk and install in my android device then app getting crash after showing Splash screen.
i'm getting below error:

2022-05-27 17:41:08.458 14784-14844/com.app.packagename
E/AndroidRuntime: FATAL EXCEPTION: create_react_context
Process: com.app.locovery, PID: 14784
java.lang.AbstractMethodError: abstract method "boolean com.facebook.soloader.nativeloader.NativeLoaderDelegate.loadLibrary(java.lang.String,
int)"
at com.facebook.soloader.nativeloader.NativeLoader.loadLibrary(NativeLoader.java:51)
at com.facebook.soloader.nativeloader.NativeLoader.loadLibrary(NativeLoader.java:30)
at com.facebook.jni.HybridData.(HybridData.java:34)
at com.facebook.react.bridge.WritableNativeMap.initHybrid(Native Method)
at com.facebook.react.bridge.WritableNativeMap.(WritableNativeMap.java:71)
at com.facebook.react.jscexecutor.JSCExecutorFactory.create(JSCExecutorFactory.java:25)
at com.facebook.react.ReactInstanceManager$5.run(ReactInstanceManager.java:1017)
at java.lang.Thread.run(Thread.java:923)

Previously i'm able to generate release build and its working fine but i have updated streamchat version and now release apk crashing.
Below is the version i have updated:
Old Version:
"react-native": "0.63.2",
"react-native-animatable": "^1.3.3",
"react-native-reanimated": "^1.13.1",
"stream-chat": "^2.7.2",
"stream-chat-react-native": "2.0.0",
New Version
"react-native": "0.63.2",
"react-native-animatable": "^1.3.3",
"react-native-reanimated": "2.6.0",
"stream-chat": "6.3.0",
"stream-chat-react-native": "4.3.1",


text:
Q: Filtering an array of dictionaries that contains a particular keyword I am retrieving data from the server,a search functionality is used.The data is an array of dictionaries like
{
 text : Some simple text,
 searchword : Apple text with new features,
 keyword : Normal words
 }
{
 text : Random,
 searchword : Newly generated text,
 keyword : Normal words
}
{
 text : Some simple word,
 searchword : Latest version,
 keyword : Normal words
}

I need to filter out like for any keys in all dictionaries if value contains "text"

A: You can try the following code:
NSMutableArray *filteredArray = [NSMutableArray array];
for (NSDictionary *dictionary in initialArray) {
    NSMutableDictionary *filteredDictionary = [NSMutableDictionary dictionary];

    [dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSString *text = (NSString *)obj;

        if ([text rangeOfString:@"text"].location == NSNotFound) {
            [filteredDictionary addObject:obj forKey:key];
        }
    }];

    [filteredArray addObject:filteredDictionary];
}

A: Well it is very simple just assuming that below is your array of dictinary:-
for (NSDictionary *dc in yourArr)
{
    NSArray *yourArr)=[dc allValues];
    for (i=0; i<[arry count]; i++)
    {
        if ([[yourArr objectAtIndex:i] isEqualToString:@"text"])
        {
            NSLog(@"found");
        }
    }
}


text:
Q: Setting dynamic baseUrl for Get Request RestClient I am wanting to dynamically change my baseUrl for my RestClient depending on what token is being run.
This is for the deputy roster systems attempting to get Roster data out but cannot figure out how to get a custom baseUrl for each token
public List<DeputyRosterData> RosterData(string url, int? actual, int? roster)
{
        BaseUrl = "e1f5c520093734.au.deputy.com";      //Error on this line but to show you what I need
        var request = Request("/api/v1/resource/Roster");
        var result = _client.Execute<List<DeputyRosterData>>(request);
        return result.Data;
}

A: I think, It's useful for u
        var client = new RestClient();
        string baseURL = "http://northwind.servicestack.net";
        string apiURL = baseURL + "/" + "customers?format=json";
        client = new RestClient(apiURL); // 1 URL
        var request = new RestRequest(Method.GET);
        IRestResponse response = client.Execute(request);
        baseURL = "https://jsonplaceholder.typicode.com";
        apiURL = baseURL + "/posts/1";
        client = new RestClient(apiURL);//2 URL
        request = new RestRequest(Method.GET);
        response = client.Execute(request);


text:
Q: How to use regex for replacing html meta tags I want to read a xhtml document by using an xml parser.
The problem is that the given document is not really valid because it has characters in the content attribute of its meta tags which must be entities:
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>My page</title>
    <meta name="dc:title" content="This is <my> example" />
    <meta name="dc:publisher" content="A&B" />
  </head>
</html>

Now I have the idea to read the content with f.e. the BufferedReader first, look for the meta tags and convert to entities.
Only then I will hand over the "corrected" document to the parser.
But I have some problems to find a possible regular expression to do the work.


text:
Q: Broken Buttons in Create User Task Flow when accessed from Self Service Tab I am working on setting a Dashboard Box on the Identity Self Service Home using sandboxes in OIM (11gr2ps3). The purpose of this box is to call the Create User form. And while it opens correctly, the Cancel and Submit buttons from the form will not close the tab (however, the submit button will submit and create a user correctly).
This is how I called the task flow:
(\oracle\iam\ui\homepage\home\pages\mdssys\cust\site\site\self-service-home.jsff.xml)
<mds:insert parent="gr2" position="last">
   <af:gridCell xmlns:af="http://xmlns.oracle.com/adf/faces/rich" id="e2545093324" halign="center">
      <oim:DashboardBox xmlns:oim="/componentLib1" titleText="#{uiBundle['CREATE_USER_HEADER']}" image="/images/Dashboard/myAccess.png" hoverImage="/images/Dashboard/myAccess_s2.png" iconClickable="true" id="db2545093324"
      iconClickAction="#{backingBeanScope.dashboardNavigationBean.launchTaskFlow}">
         <af:clientAttribute xmlns:af="http://xmlns.oracle.com/adf/faces/rich" name="taskFlowId" value="/WEB-INF/oracle/iam/ui/taskflows/public/tfs/create-user-tf.xml#create-user-tf"/>
         <af:clientAttribute xmlns:af="http://xmlns.oracle.com/adf/faces/rich" name="title" value="#{uiBundle['CREATE_USER_HEADER']}"/>
      </oim:DashboardBox>
   </af:gridCell>
</mds:insert>

The logs do not leave any error when clicking on the cancel button, although it seems that the managed beans might be refreshing.
Any ideas? Is there any other attribute or customization I should add to, perhaps, the catalog files in order for them to close the task flow and tab correctly?
Update:
I tried making a task flow launcher by raising a contextual event as suggested and using the documentation that Amr Gawish shared. It is called by updating the iconClickAction attribute of the Dashboard Box with the new bean. Here is the method I created:
public void launchCreateUserTaskFlow(ActionEvent evt) {
    ResourceBundle bundle = ResourceBundle.getBundle(OIM_USR_BUNDLE, locale);

    String taskFlowId = "/WEB-INF/oracle/iam/ui/taskflows/public/tfs/create-user-tf.xml#create-user-tf";
    String id = "create_user";
    String name = bundle.getString("CREATE_USER_HEADER");

    String jsonPayLoad = TaskFlowUtils.createContextualEventPayLoad(id, taskFlowId, name);
    TaskFlowUtils.raiseContextualEvent(TaskFlowUtils.RAISE_TASK_FLOW_LAUNCH_EVENT, jsonPayLoad);
}

It kind of worked, but only halfway. The Cancel button will close the tab correctly every time, but the Submit button will only close the tab when the request does not leave a Request ID. Any ideas?


text:
Q: Linqpad data transfer from entity objects to database Using LinqPad I have mapped XML to database entities, entities provided by LinqPad.
After mapping all the data, I now have over 5 million entities in memory. I am transferring 1000 entities at a time via batch insert (InsertAllOnSubmit). But its hovering over 10 seconds per SubmitChanges().
To transfer all 5 million records, it looks like a day or more.
How can I optimise this, so it happens faster?

A: For transferring so many records, apparently Linq-to-entities was a bad choice. I did it thru stored procedures and the transfer completed in 4 hrs.


text:
Q: Android replace fragment fast I am trying to find a way to replace fragments as fast as I can. The problem is with fragment recreation (inflating layout on recreation).
Why is this a bad idea?
private View view;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    if (view == null)
    {
        view= inflater.inflate(R.layout.fragment_one, container, false);

        Log.e(TAG, "On create view !");
    }

    return view;
}

Or this variant:
User click on a tab from actionbar
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft)
{
    // tab contains a tag with the name of the Fragment, in this case is FRAGMENT_ONE
    TabDataHolder tdh = (TabDataHolder) tab.getTag();
    replaceFragment(R.id.mainContent, tdh.fragmentTag);
}

Method for replacing fragment:
    private void replaceFragment(int fragmentContainerId, String fragmentTag)
    {
        Log.e(TAG, "Replace fragment !");

        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);

        ft.replace(fragmentContainerId, getFragment(fragmentTag), fragmentTag).commit();
    }

Method which creates or returns an existing fragment
    private Fragment getFragment(String fragmentTag)
    {
        Fragment fg = getFragmentManager().findFragmentByTag(fragmentTag);
        if (fg == null)
            fg = getFragmentFromStack(fragmentTag);

        if (fragmentTag.equals(FRAGMENT_ONE))
        {
            if (fg == null)
            {
                fg = new FragmentOne();

                addFragmentToStack(fg, fragmentTag, false);

                Log.e(TAG, "Adding fg to stack !");
            }
        }
        else
        if (fragmentTag.equals(FRAGMENT_TWO))
        {
            if (fg == null)
            {
                fg = new FragmentTwo();

                addFragmentToStack(fg, fragmentTag, false);

                Log.e(TAG, "Adding fg to stack !");
            }
        }
        else
        if (fragmentTag.equals(FRAGMENT_THREE))
        {
            if (fg == null)
            {
                fg = new FragmentThree();

                addFragmentToStack(fg, fragmentTag, false);

                Log.e(TAG, "Adding fg to stack !");
            }
        }
        else
        if (fragmentTag.equals(FRAGMENT_FOUR))
        {
            if (fg == null)
            {
                fg = new FragmentFour();

                addFragmentToStack(fg, fragmentTag, false);

                Log.e(TAG, "Adding fg to stack !");
            }
        }

        if (fg == null)
            new NullPointerException("Fragment not found");

        return fg;
    }

Method which returns an existing fragment from the stack (ArrayList) by tag
    private ArrayList<FragmentData> fragmentDataStack = new ArrayList<FragmentData>();

    private Fragment getFragmentFromStack(String fragmentTag)
    {
        for (FragmentData fgd : fragmentDataStack)
        {
            if (fgd.getTag().equals(fragmentTag))
                return fgd.getFragment();
        }

        return null;
    }

public class FragmentData
{
private Fragment fragment;
private String tag;

public FragmentData (Fragment fragment, String tag)
{
    this.fragment = fragment;
    this.tag = tag;
}

public Fragment getFragment() {
    return fragment;
}

public void setFragment(Fragment fragment) {
    this.fragment = fragment;
}

public String getTag() {
    return tag;
}

public void setTag(String tag) {
    this.tag = tag;
}

}
Method which will add a Fragment to the stack. The last parameter is for deleting the old fragment and adding a new fragment
private void addFragmentToStack(Fragment fragment, String fragmentTag, boolean replaceIfExists)
{
    if (replaceIfExists)
    {
        for (int i = 0; i < fragmentDataStack.size(); i++)
        {
            if (fragmentDataStack.get(i).getTag().equals(fragmentTag))
            {
                fragmentDataStack.set(i, new FragmentData(fragment, fragmentTag));
                return;
            }
        }
    }

    fragmentDataStack.add(new FragmentData(fragment, fragmentTag));
}

I am not sure if this the right procedure for fast fragment replacement.


text:
Q: plane given with a line on it -> build a rectangle in the plane with the line as the diagonal of the rectangle (in 3D) (Everything's in 3D) Firstly a plane is given. On this plane I'm drawing a line. The beginning and ending point of the line is given therefore. What I have to do is to use the line as the diagonal of the rectangle to create the rectangle. For this I just need the other two missing points which are also in the very same plane I've got.
How can I determine the missing two points?
In 2D for example if you have like point B (6|4) and C (1|2) then you can conclude that A is on (1|4) and D is on (6|2).
But I struggle to find a method/algorithm to do so in a 3D world.
PS: If I used the wrong tag please tell me another suggestion, thx!

A: To show that infinite number of rectangles with common diagonal does exist in the same plane:
You have vertices A and C,  and plane normal vector n, and want to determine vertices B and D.
Let B = (bx, by, bz) (unknown)
Condition of perpendicularity of AB and BC edges: dot product of vectors is zero.
 (bx-ax) * (bx-сx) + (by-ay) * (by-сy) + (bz-az) * (bz-сz) = 0

Condition of "B lies in the plane": dot product of AB and normal is zero
 (bx-ax) * nx + (by-ay) * ny + (bz-az) * nz = 0

So you have two linear equations for three unknowns bx, by, bz - infinite number of solutions.
Perhaps you might have some additional condition/restriction to define solution uniquely (as axis-aligned rectangle in your 2d example)
Edit:
Arbitrary possible variant: let AB edge is parallel to OXY plane, so it is perpendicular to OZ axis, and the third equation is
 (bx-ax) * 0 + (by-ay) * 0 + (bz-az) * 1 = 0, so
 (bz - az) = 0

and you can substitute this expression and solve system for two unknowns bx and by
 (bx-ax) * (bx-сx) + (by-ay) * (by-сy) = 0
 (bx-ax) * nx + (by-ay) * ny = 0


text:
Q: Выборка many to many Yii2 Делаю скриптик на Yii2.
Есть четыре таблицы (files, permissions, banks, regions).
Из таблицы files нужно выбрать только те записи, к которым у юзера есть доступ, и вывести в GridView.
Таблица files:
`files`.`id` - id файла
`files`.`bank_id` - к какому банку принадлежит файл
`files`.`region_id` - к какому региону принадлежит файл'

Таблица permissions:
`permissions`.`user_id` - кому предоставлять доступ
`permissions`.`bank` - к какому банку
`permissions`.`region` - к какому региону
`permissions`.`file` - к какому файлу

В общем, нужно сделать такую выборку в Yii2:
SELECT * FROM `files`
LEFT JOIN `permissions` ON('permissions`.`user_id` = _16_)
WHERE(
       (`permissions`.`file`=`files`.`id`)
     or
       (`permissions`.`bank` = `files`.`bank_id`)
     or
       (`permissions`.`region` = `files`.`region_id`)
)

A: к many-to-many вопрос не имеет никакого отношения вам нужно
$model = $connection->createCommand('SELECT * FROM `files`
LEFT JOIN `permissions` ON('permissions`.`user_id` = _16_)
   WHERE(
   (`permissions`.`file`=`files`.`id`)
 or
   (`permissions`.`bank` = `files`.`bank_id`)
 or
   (`permissions`.`region` = `files`.`region_id`)
   )');

$sql = $model->queryAll();

а про связь many-to-many для yii 2 можно прочитать здесь


text:
Q: integer-matching regex pattern not working I try to check whenever the input string is an integer, but nothing returns positive result with the pattern I created.
#include <iostream>
#include <string>
#include <regex>
using namespace std;

int main()
{
    string input = "1";
    string int_num = "^0$|^[1-9][0-9]*$";

    regex pattern(int_num, regex_constants::grep);

    if(regex_match(input, pattern))
        cout << "matched\n";
    else
        cout << "not matched\n";

    return 0;
}

A: The reason your pattern doesn't work is because you've specified that the regex should emulate greps grammar.
If you remove that flag from your regex definition, your pattern works correctly:
string int_num = "^0$|^[1-9][0-9]*$";
regex pattern(int_num);

Here's an example of the modified script: https://ideone.com/iETnsw
If you must specify a regex grammar, use ECMAScript, not grep.

A: This works for me,  although your version also seems to be correct according to ECMAScript regex syntax.
"^(0|[1-9][0-9]*)$"

A: First of all, regex pattern should be changed to "^(0|[1-9][0-9]*)$" because it looks better. Then, change regex_constants::grep to regex_constants::ECMAScript, or leave blank, because ECMAScript is default. At the end, it is required to compile with g++-4.9, because g++-4.8 version doesn't work with regex lib.

A: Using Regex101.com, you can tell that your expression is not matching numbers. You can match a number by using the expression \d+.
Another way of verifying integers, would be doing something like this:
int y;
cin >> y;

if (cin.fail()) {
    //Is not an integer
}

A: I think the best way would be to iterate through each character to check if they are digit and if it reaches the end, then it is a number. Maybe somwthing like would help. Haven't tested though.
string::const_iterator it = str.begin();

while(it != str.end() && isdigit(*it))
{
    it++;
}

if (!str.empty() && it == str.end())
    cout << "not a string";
else
    cout << "valid";

A: You have to remove the grammar specification as grep, then it will work.
int main()
    {
        std::string input = "1";
    std::regex pattern ("^0$|^[1-9][0-9]*$");

      if(regex_match(input, pattern))
        cout << "matched\n";
    else
        cout << "not matched\n";

    return 0;
}

output: matched


text:
Q: InfoPath 2013 web form doesn't open the browse dialog in the people picker control I have a user picker control, which when used in preview mode open a dialog to find users when I click on the browse button,
but do nothing when deployed on the SharePoint server.
If i type a user in the input box, the check names button is working and provide multiple choice when it's the case.
As the people picker control was modified in the new SharePoint 2013, could it be a side effect ?
Does anyone have the same problem ?

A: It worked once I enabled the ribbon in the form options.
Form Options -> Web Browser -> checked  Show InfoPath commands in Ribbon or toolbar

A: Finally got the solution when you disable the ribbon the the browse button is also disabled to overcome this problem

*

*Create a new blank page or a wiki page.

*Insert a InfoPath Form WebPart and link this webPart to the desired form.

*Now after doing all the changes you can see that the form gets loaded and when you click the browse button it should function normally.

*If you want the same look of the form as it is when you open in it in new page or a tab, use a CEWP and add styles to disable unwanted controls like the navigation menus, search bar etc.,


text:
Q: I can't show by database single row data? i want to show database single row data by unique_id. But i can't.
my query is...
"SELECT * FORM `signup` WHERE `uniqueId`=" . $singleRowUniqId

A: Seems like, it's a typo. Change FORM to FROM.
Ultimately, it would be like select columnNames from tableName where ColumnId='$variableId'

A: This query should solve you problem (as others said) but I additionally added mysql_escape_string to deny sql injection:
"SELECT * FROM `signup` WHERE `uniqueId`= ".mysql_escape_string($singleRowUniqId)

A: Please use this query. your query is wrong, use this query.
 "SELECT * FROM `signup` WHERE `uniqueId`=" . $singleRowUniqId

A: You misstyped "FORM" insteed "FROM"


text:
Q: Find Most Frequently-used Java Methods in Eclipse Workspace Is there an Eclipse plug-in, or some other tool or technique that would search an entire Java project (and/or the entire workspace) and reveal (in list/sortable format) the frequency-of-invocation of all public methods in the project?  That is "what code is using what other code" the most?
I'm very familiar with the CTRL-SHIFT-G or CTRL-G usage; use it all the time.  I'm also familiar with the Call Hierarchy view.  The result that I'm looking for could be described like doing Search > References > Workspace (CTRL-SHIFT-G) on every method in every class in the workspace and tallying/counting the number of results each time, with final, sortable output like the example below.
The notion above is to get an idea of which classes/methods are getting most-used (not at run-time; in this question "used" != "executed"), in order to prioritize unit-testing on a very large project.  I want to start using JUnit more (more than not-at-all, that is), and the idea of finding the most-used methods seemed like a good place to start.
For example, given three classes, ClassA, ClassB, and ClassC, I'd like a summary similar to this:

    Method                                       Number of calls
    ClassB.methodThatDoesSomethingMundane()                  134
    ClassC.methodThatDoesCoolStuff()                          78
    ClassC.methodThatDoesImportantThing()                     71
    ClassA.constructor()                                      63
    ClassB.aDifferentBoringMethod()                           37
    ClassA.getSomething()                                     19
    ... etc ...

A: JArchitect, a commercial product, seems to have an interesting metrics module:

Method rank: MethodRank values are computed by applying the Google PageRank algorithm on the graph of methods' dependencies. A homothety of center 0.15 is applied to make it so that the average of MethodRank is 1.
Recommendations: Methods with high MethodRank should be more carefully tested because bugs in such methods will likely be more catastrophic.

I did not test it, but it worth a try.
But I don't think it will work if you use Java reflection.

A: You could use a profiler (for example VisualVM, jvisualvm.exe in jdk/bin/ folder) for that.


text:
Q: Shadow primary key I want create a table with a primary key shadowed (out of the model).
public class Person
{
    public string Name { get; set; }
}

public class PersonEntityTypeConfiguration : IEntityTypeConfiguration<Person>
{
    public void Configure(EntityTypeBuilder<Person> builder)
    {
        builder.Property?
        builder.HasKey("Id")????
    }
}

Note: the real case is a different class and a value object (DDD).

A: I don't use the TypeBuilder a lot but this should be close:
public void Configure(EntityTypeBuilder<Person> builder)
{
    builder.Property<int>("id");
    builder.HasKey("Id");
}

A: There are two ways to get this done. One is to define the property and then configure it as key (the order matters)
builder.Property<int>("ID")
    .HasColumnType("int")
    .ValueGeneratedOnAdd();
builder.HasKey("ID");

You probably want ValueGeneratedOnAddhere, because it's more or less the point of shadow properties to do everything under the hood.
I never like code in which the order of statements is a hidden requirement. It may lead to unexpected bugs. I would prefer the single-statement option:
builder.Property<int>("ID")
    .HasColumnType("int")
    .ValueGeneratedOnAdd()
    .HasAnnotation("Key", 0);

The value 0 in HasAnnotation is entered because it's mandatory. It has no bearing on the key generation.
I'm not yet sure if it's a good idea to use shadow properties in keys. I can't oversee which issues may appear when actually working with them. It may be a very good idea indeed.


text:
Q: Delphi XE2 64-bit extremely slow runtime performance on string routines I'm porting some applications from 32 to 64 bits delphi, which do a lot of text processing, and noticed an extreme change in processing speed. Did some tests with a few procedures, for example, this takes already more than 200% the time in 64bits than compiling to 32 (2000+ ms compared to ~900)
Is this normal?
function IsStrANumber(const S: AnsiString): Boolean;
var P: PAnsiChar;
begin
  Result := False;
  P := PAnsiChar(S);
  while P^ <> #0 do begin
    if not (P^ in ['0'..'9']) then Exit;
    Inc(P);
  end;
  Result := True;
end;

procedure TForm11.Button1Click(Sender: TObject);
Const x = '1234567890';
Var a,y,z: Integer;
begin
  z := GetTickCount;
  for a := 1 to 99999999 do begin
   if IsStrANumber(x) then y := 0;//StrToInt(x);
  end;
  Caption := IntToStr(GetTickCount-z);
end;

A: Try to avoid any string allocation in your loop.
In your case, the stack preparation of the x64 calling convention could be involved. Did you try to make IsStrANumber declared as inline?
I guess this will make it faster.
function IsStrANumber(P: PAnsiChar): Boolean; inline;
begin
  Result := False;
  if P=nil then exit;
  while P^ <> #0 do
    if not (P^ in ['0'..'9']) then
      Exit else
      Inc(P);
  Result := True;
end;

procedure TForm11.Button1Click(Sender: TObject);
Const x = '1234567890';
Var a,y,z: Integer;
    s: AnsiString;
begin
  z := GetTickCount;
  s := x;
  for a := 1 to 99999999 do begin
   if IsStrANumber(pointer(s)) then y := 0;//StrToInt(x);
  end;
  Caption := IntToStr(GetTickCount-z);
end;

The "pure pascal" version of the RTL is indeed the cause of slowness here...
Note that it is even worse with FPC 64 bit compiler, when compared to the 32 bit version... Sounded that the Delphi compiler is not the only one! 64 bit does not mean "faster", whatever marketing says! It is sometimes even the contrary (e.g. the JRE is known to be slower on 64 bit, and a new x32 model is to be introduced in Linux when it comes about pointer size).

A: The code can be written like this with good perfomance results:
function IsStrANumber(const S: AnsiString): Boolean; inline;
var
  P: PAnsiChar;
begin
  Result := False;
  P := PAnsiChar(S);
  while True do
  begin
    case PByte(P)^ of
      0: Break;
      $30..$39: Inc(P);
    else
      Exit;
    end;
  end;
  Result := True;
end;

Intel(R) Core(TM)2 CPU T5600 @ 1.83GHz

*

*x32-bit : 2730 ms

*x64-bit : 3260 ms

Intel(R) Pentium(R) D CPU 3.40GHz

*

*x32-bit : 2979 ms

*x64-bit : 1794 ms

Unwinding the above loop can result to faster execution:
function IsStrANumber(const S: AnsiString): Boolean; inline;
type
  TStrData = packed record
    A: Byte;
    B: Byte;
    C: Byte;
    D: Byte;
    E: Byte;
    F: Byte;
    G: Byte;
    H: Byte;
  end;
  PStrData = ^TStrData;
var
  P: PStrData;
begin
  Result := False;
  P := PStrData(PAnsiChar(S));
  while True do
  begin
    case P^.A of
      0: Break;
      $30..$39:
        case P^.B of
          0: Break;
          $30..$39:
            case P^.C of
              0: Break;
              $30..$39:
                case P^.D of
                  0: Break;
                  $30..$39:
                    case P^.E of
                      0: Break;
                      $30..$39:
                        case P^.F of
                          0: Break;
                          $30..$39:
                            case P^.G of
                              0: Break;
                              $30..$39:
                                case P^.H of
                                  0: Break;
                                  $30..$39: Inc(P);
                                else
                                  Exit;
                                end;
                            else
                              Exit;
                            end;
                        else
                          Exit;
                        end;
                    else
                      Exit;
                    end;
                else
                  Exit;
                end;
            else
              Exit;
            end;
        else
          Exit;
        end;
    else
      Exit;
    end;
  end;
  Result := True;
end;

Intel(R) Core(TM)2 CPU T5600 @ 1.83GHz

*

*x32-bit : 2199 ms

*x64-bit : 1934 ms

Intel(R) Pentium(R) D CPU 3.40GHz

*

*x32-bit : 1170 ms

*x64-bit : 1279 ms

If you also apply what Arnaud Bouchez said you can make it even faster.

A: There is no current solution for this, as it is caused by the fact that the code for most of the string routines in 64 bit is compiled with PUREPASCAL defined, IOW, it is plain Delphi, no assembler, while the code for many of the important string routines in 32 bit was done by the FastCode project, and in assembler.
Currently, there are no FastCode equivalents in 64 bit, and I assume that the developer team will try to eliminate assembler anyway, especially since they are moving to more platforms.
This means that optimization of the generated code becomes more and more important. I hope that the announced move to an LLVM backend will speed up much of the code considerably, so pure Delphi code is not such a problem anymore.
So sorry, no solution, but perhaps an explanation.
Update
As of XE4, quite a few FastCode routines have replaced the unoptimized routines I talk about in the above paragraphs. They are usually still PUREPASCAL, but yet they represent a good optimization. So the situation is not as bad as it used to be. The TStringHelper and plain string routines still display some bugs and some extremely slow code in OS X (especially where conversion from Unicode to Ansi or vice versa is concerned), but the Win64 part of the RTL seems to be a lot better.

A: The test p^ in ['0'..'9'] is slow in 64-bit.
Added an inlined function with a test for lower/upper boundary instead of the in [] test, plus a test for an empty string.
function IsStrANumber(const S: AnsiString): Boolean; inline;
var
  P: PAnsiChar;
begin
  Result := False;
  P := Pointer(S);
  if (P = nil) then
    Exit;
  while P^ <> #0 do begin
    if (P^ < '0') then Exit;
    if (P^ > '9') then Exit;
    Inc(P);
  end;
  Result := True;
end;

Benchmark results:
        x32     x64
--------------------
hikari  1420    3963
LU RD   1029    1060

In 32 bit, main speed difference is inlining and that P := PAnsiChar(S); will call an external RTL routine for a nil check before assigning the pointer value, while P := Pointer(S); just assigns the pointer.
Observing that the goal here is to test if a string is a number and then convert it,
why not use the RTL TryStrToInt(), which does all in one step and handles signs,blanks as well.
Often when profiling and optimizing routines, the most important thing is to find the right approach to the problem.

A: The benefit of 64-bit is in address space, not speed (unless your code is limited by addressable memory).
Historically, this sort of character manipulation code has always been slower on wider machines.  It was true moving from the 16-bit 8088/8086 to the 32-bit 386.  Putting an 8-bit char in a 64-bit register is a waste of memory bandwidth & cache.
For speed, you can avoid char variables, use pointers, use lookup tables, use bit-parallelism (manipulate 8 chars in one 64-bit word), or use the SSE/SSE2... instructions.  Obviously, some of these will make your code CPUID dependent.  Also, open the CPU window while debugging, and look for the compiler doing stupid things "for" you like silent string conversions (especially around calls).
You might try looking at some of the native Pascal routines in the FastCode Library.  E.G. PosEx_Sha_Pas_2, while not as fast as the assembler versions, is faster than the RTL code (in 32-bits).

A: Here are two functions. One checks only for positive numbers. The second checks for negative aswell. And is not limited to size. The second one is 4x faster than regular Val.
function IsInteger1(const S: String): Boolean; overload;
var
  E: Integer;
  Value: Integer;
begin
  Val(S, Value, E);
  Result := E = 0;
end;

function IsInteger2(const S: String): Boolean; inline;
var
    I: Integer;
begin
    Result := False;
    I := 0;
  while True do
  begin
    case Ord(S[I+1]) of
      0: Break;
      $30..$39:
        case Ord(S[I+2]) of
          0: Break;
          $30..$39:
            case Ord(S[I+3]) of
              0: Break;
              $30..$39:
                case Ord(S[I+4]) of
                  0: Break;
                  $30..$39:
                    case Ord(S[I+5]) of
                      0: Break;
                      $30..$39:
                        case Ord(S[I+6]) of
                          0: Break;
                          $30..$39:
                            case Ord(S[I+7]) of
                              0: Break;
                              $30..$39:
                                case Ord(S[I+8]) of
                                  0: Break;
                                  $30..$39:
                                    case Ord(S[I+9]) of
                                      0: Break;
                                      $30..$39:
                                        case Ord(S[I+10]) of
                                          0: Break;
                                          $30..$39: Inc(I, 10);
                                        else
                                          Exit;
                                        end;
                                    else
                                      Exit;
                                    end;
                                else
                                  Exit;
                                end;
                            else
                              Exit;
                            end;
                        else
                          Exit;
                        end;
                    else
                      Exit;
                    end;
                else
                  Exit;
                end;
            else
              Exit;
            end;
        else
          Exit;
        end;
    else
      Exit;
    end;
  end;
  Result := True;
end;

function IsInteger3(const S: String): Boolean; inline;
var
  I: Integer;
begin
  Result := False;
  case Ord(S[1]) of
    $2D,
    $30 .. $39:
    begin
      I := 1;
      while True do
      case Ord(S[I + 1]) of
        0:
        Break;
        $30 .. $39:
        case Ord(S[I + 2]) of
          0:
          Break;
          $30 .. $39:
          case Ord(S[I + 3]) of
            0:
            Break;
            $30 .. $39:
            case Ord(S[I + 4]) of
              0:
              Break;
              $30 .. $39:
              case Ord(S[I + 5]) of
                0:
                Break;
                $30 .. $39:
                case Ord(S[I + 6]) of
                  0:
                  Break;
                  $30 .. $39:
                  case Ord(S[I + 7]) of
                    0:
                    Break;
                    $30 .. $39:
                    case Ord(S[I + 8]) of
                      0:
                      Break;
                      $30 .. $39:
                      case Ord(S[I + 9]) of
                        0:
                        Break;
                        $30 .. $39:
                        case Ord(S[I + 10]) of
                          0:
                          Break;
                          $30 .. $39:
                          case Ord(S[I + 11]) of
                            0:
                            Break;
                            $30 .. $39:
                            case Ord(S[I + 12]) of
                              0:
                              Break;
                              $30 .. $39:
                              case Ord(S[I + 13]) of
                                0:
                                Break;
                                $30 .. $39:
                                Inc(I, 13);
                              else
                                Exit;
                              end;
                            else
                              Exit;
                            end;
                          else
                            Exit;
                          end;
                        else
                          Exit;
                        end;
                      else
                        Exit;
                      end;
                    else
                      Exit;
                    end;
                  else
                    Exit;
                  end;
                else
                  Exit;
                end;
              else
                Exit;
              end;
            else
              Exit;
            end;
          else
            Exit;
          end;
        else
          Exit;
        end;
      else
        Exit;
      end;
    end;
  else
    Exit;
  end;
  Result := True;
end;


text:
Q: Spark RDD method "saveAsTextFile" throwing exception Even after deleting the output directory. org.apache.hadoop.mapred.FileAlreadyExistsException I am calling this method on an RDD[String] with destination in the arguments. (Scala)
Even after deleting the directory before starting, the process gives this error.
I am running this process on EMR cluster with output location at aws S3.
Below is the command used:
spark-submit --deploy-mode cluster --class com.hotwire.hda.spark.prd.pricingengine.PRDPricingEngine --conf spark.yarn.submit.waitAppCompletion=true --num-executors 21 --executor-cores 4 --executor-memory 20g --driver-memory 8g --driver-cores 4 s3://bi-aws-users/sbatheja/hotel-shopper-0.0.1-SNAPSHOT-jar-with-dependencies.jar -d 3 -p 100 --search-bucket s3a://hda-prod-business.hotwire.hotel.search --prd-output-path s3a://bi-aws-users/sbatheja/PRD/PriceEngineOutput/

Log:
16/07/07 11:27:47 INFO BlockManagerMaster: BlockManagerMaster stopped
16/07/07 11:27:47 INFO OutputCommitCoordinator$OutputCommitCoordinatorEndpoint: OutputCommitCoordinator stopped!
16/07/07 11:27:47 INFO SparkContext: Successfully stopped SparkContext
16/07/07 11:27:47 INFO ApplicationMaster: Unregistering ApplicationMaster with FAILED (diag message: User class threw exception: **org.apache.hadoop.mapred.FileAlreadyExistsException: Output directory s3a://bi-aws-users/sbatheja/PRD/PriceEngineOutput already exists)**
16/07/07 11:27:47 INFO RemoteActorRefProvider$RemotingTerminator: Shutting down remote daemon.
16/07/07 11:27:47 INFO RemoteActorRefProvider$RemotingTerminator: Remote daemon shut down; proceeding with flushing remote transports.
16/07/07 11:27:47 INFO AMRMClientImpl: Waiting for application to be successfully unregistered.
16/07/07 11:27:47 INFO RemoteActorRefProvider$RemotingTerminator: Remoting shut down.
16/07/07 11:27:47 INFO ApplicationMaster: Deleting staging directory .sparkStaging/application_1467889642439_0001
16/07/07 11:27:47 INFO ShutdownHookManager: Shutdown hook called
16/07/07 11:27:47 INFO ShutdownHookManager: Deleting directory /mnt/yarn/usercache/hadoop/appcache/application_1467889642439_0001/spark-7f836950-a040-4216-9308-2bb4565c5649

It creates "_temporary" directory in the location, which contains empty part files.

A: In short, a word:
Make sure the scala version of spark-core and scala-library is consistent.

I encountered the same problem.
As I saving the file to the HDFS, it throws an exception: org.apache.hadoop.mapred.FileAlreadyExistsException
Then I checked the HDFS file directory, there is a empty temporary folder: TARGET_DIR/_temporary/0.
You can submit the job, open the detailed configuration:./spark-submit --verbose.
 And then look at the full context and log, there must be other errors caused.
My job in the RUNNING state, the first error is thrown:
17/04/23 11:47:02 ERROR executor.Executor: Exception in task 1.0 in stage 0.0 (TID 1)
java.lang.NoSuchMethodError: scala.Predef$.refArrayOps([Ljava/lang/Object;)[Ljava/lang/Object;

Then the job will be retried and re-executed. At this time, job re-implementation, it will find just the directory has been created. And also throws the directory already exists.
After confirming that the first error is version compatibility issues.
The spark version is 2.1.0, the corresponding spark-core scala version is 2.11, and the scala-library dependency of the scala version is 2.12.xx.
When the two scala version of the change is consistent (usually modify the scala-library version), you can solve the first exception problem, then job can be normal FINISHED.
pom.xml example:
<!-- Spark -->
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-core_2.11</artifactId>
    <version>2.1.0</version>
</dependency>
<!-- scala -->
<dependency>
    <groupId>org.scala-lang</groupId>
    <artifactId>scala-library</artifactId>
    <version>2.11.7</version>
</dependency>


text:
Q: Network Monitor: Don't Show Same Line Immediately Twice I am building a networking monitoring script in bash. The base command is:
sudo ettercap -T -M ARP -i en1 /// | egrep --color Referer:

My output looks like
* |==================================================>| 100.00 %

Referer: http://www.apple.com/.
Referer: http://www.apple.com/.
Referer: http://www.apple.com/.
Referer: http://www.apple.com/.
Referer: http://www.apple.com/diversity/.

My desired output is:
* |==================================================>| 100.00 %

Title: Apple
URL: http://www.apple.com/

Title: Apple - Diversity - Inclusion inspires innovation.
URL: http://www.apple.com/diversity/

Notice: . at the end of a Referer is no longer there, Referer is changed to URL, Title is added based on title of HTML page and there is a new line every Title URL pair. In my previous question, I was provided with a perl script to do something along these lines, however ettercap didn't always show a Host: and GET line, so I am retrying with it's constant Referer line. I am not familiar with perl at all, so I am unable to edit myself. If you could comment what everything does, that would make it easier for me to learn.
Any help is greatly appreciated, thanks!


text:
Q: Get JavaScript to ignore everything that is not a letter How would I get JS to ignore everything that is not a letter (e.g. abc...) without using regex.
Examples
match("abcdef","@C2D!") returns true
match("abcdef","CAfe") returns true
match("abcdef","CG") returns false

This is what I've done so far...
function match(string, pattern) {
    string = string.toLowerCase();
    pattern = pattern.toLowerCase();
    for (var i = 0, l = string.length; i < l; ++i) {
        if(pattern.indexOf(string[i]) === -1) return false;
    }
    return true;
}
alert(match("abcdef", "@C2D!"));

Fiddle here: http://jsfiddle.net/5UCwW/

A: Use a regular expression like the following [^A-Za-z].
var re = /[^A-Za-z]/g;

function match(string, pattern) {
    string = string.toLowerCase();
    pattern = pattern.toLowerCase().replace(re, "");
    for (var i = 0, l = string.length; i < l; ++i) {
        if(pattern.indexOf(string[i]) === -1) return false;
    }
    return true;
}

As a function without reg ex
var sanitize = function (str) {
  var newStr = "", i, charCode;

  for (i = 0; i < str.length; ++i) {
    charCode = str.charCodeAt(i);
    if (charCode >= 65 && charCode <= 90 ||
        charCode >= 97 && charCode <= 122)  {
      newStr += str[i];
    }

  return newStr;
}

EDIT: A-z uses the range of the ascii values from capital a to small case z. Thus this includes ], \, [, ^, _ and `. I was not aware of this, [A-Za-z] is the correct pattern.

A: Use Javascript's built-in match method on strings:
 var mystring = '@C2D!';
 mystring.match(/[^a-zA-Z]/gi).length returns true

and
 var mystring2 = 'abcdef';
 mystring2.match(/[^a-zA-Z]/gi).length returns false

I'm assuming you're looking for lower and upper-case letters.  If just lower, use [^a-z].
For more info on the match method, go here:
http://www.w3schools.com/jsref/jsref_match.asp


text:
Q: Fmin can't convert expression to float I wrote a program that firstly calculates Inverse Laplace transform then calculates least squares and at the end it should minimize the sum of those squares. Unfortunately I get this error:
Traceback (most recent call last):
  File "C:/program.py", line 46, in <module>
    LSQminsearch(f, TF, 0.5, 0.5, 0.5, 0.5)
  File "C:/program.py", line 36, in LSQminsearch
    res = optimize.fmin(f, [k0, dzeta0, tau0, tauz0], maxiter = 100000000, maxfun=1000000)
  File "C:\Users\xyz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\scipy\optimize\optimize.py", line 443, in fmin
    res = _minimize_neldermead(func, x0, args, callback=callback, **opts)
  File "C:\Users\xyz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\scipy\optimize\optimize.py", line 586, in _minimize_neldermead
    fsim[k] = func(sim[k])
  File "C:\Users\xyz\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sympy\core\expr.py", line 325, in __float__
    raise TypeError("can't convert expression to float")
TypeError: can't convert expression to float

and my code:
import pandas as pd
from sympy import  symbols, inverse_laplace_transform, sympify
from scipy import optimize

dane = pd.read_fwf('data11.txt', header=None)
dane.columns = ['time', 'response']

T = dane['time']
Yt = dane['response']

t = symbols('t', positive=True, real=True)
s, k, tauz, tau, dzeta = symbols('s k tauz tau dzeta', real=True)

F = (k * ((tauz*s + 1)/((tau**2)*(s**2) + 2*tau*dzeta*s + 1)))
print('Calculating Inverse Laplace')
IL = inverse_laplace_transform(F, s, t)

TF = sympify(IL)

LSQ = 0
print('Calculating least squares')
for i in range(len(T)):
    LSQl = Yt[i]
    LSQp = TF.subs({'t': T[i]})
    LSQk = (LSQl - LSQp)**2
    LSQ = LSQ + LSQk

LSQ = sympify(LSQ)

def f(params):
    return LSQ.subs({'k': params[0], 'dzeta': params[1], 'tau': params[2], 'tauz': params[3]})

def LSQminsearch(f, TF, k0, dzeta0, tau0, tauz0):
    print(f'Searching for minimum for k0= {k0} dzeta0= {dzeta0} tau0= {tau0} tauz0= {tauz0} ...')
    res = optimize.fmin(f, [k0, dzeta0, tau0, tauz0], maxiter = 100000000, maxfun=1000000)
    k = res[0]
    dzeta = res[1]
    tau = res[2]
    tauz = res[3]
    print(f'Found k0= {k} dzeta0= {dzeta} tau0= {tau} tauz0= {tauz} ...')

LSQminsearch(f, TF, 0.5, 0.5, 0.5, 0.5)

I have seen some of the other questions about this but most of problems with them was mixing namespaces for mathematical functions but I don't see this in my code. I cannot post here data from data11.txt because its too much characters so here it is: https://justpaste.it/6vwwl

A: Changes you need:

*

*You should replace a symbol to a number, not a string to a number

*Function f should return a float

So you should try with this:
import pandas as pd
from sympy import  symbols, inverse_laplace_transform, sympify
from scipy import optimize

dane = pd.read_fwf('data11.txt', header=None)
dane.columns = ['time', 'response']

T = dane['time']
Yt = dane['response']

t = symbols('t', positive=True, real=True)
s, k, tauz, tau, dzeta = symbols('s k tauz tau dzeta', real=True)

F = (k * ((tauz*s + 1)/((tau**2)*(s**2) + 2*tau*dzeta*s + 1)))
print('Calculating Inverse Laplace')
IL = inverse_laplace_transform(F, s, t)

TF = sympify(IL)

LSQ = 0
print('Calculating least squares')
for i in range(len(T)):
    LSQl = Yt[i]
    LSQp = TF.subs({t: T[i]})   # <-- use t, not 't'
    LSQk = (LSQl - LSQp)**2
    LSQ = LSQ + LSQk

LSQ = sympify(LSQ)

def f(params):
    # use symbols, not string
    # eval to float, be careful about complex number
    re, im = LSQ.subs({k: params[0], dzeta: params[1], tau: params[2], tauz: params[3]}).evalf().as_real_imag()
    return re

def LSQminsearch(f, TF, k0, dzeta0, tau0, tauz0):
    print(f'Searching for minimum for k0= {k0} dzeta0= {dzeta0} tau0= {tau0} tauz0= {tauz0} ...')
    res = optimize.fmin(f, [k0, dzeta0, tau0, tauz0], maxiter = 100000000, maxfun=1000000)
    k = res[0]
    dzeta = res[1]
    tau = res[2]
    tauz = res[3]
    print(f'Found k0= {k} dzeta0= {dzeta} tau0= {tau} tauz0= {tauz} ...')

LSQminsearch(f, TF, 0.5, 0.5, 0.5, 0.5)


text:
Q: Как изменить цвет у верхней и левой границы input Html

.count {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 0.1rem;
}

.count-input {
  width: 2.2rem;
  height: 2.2rem;
  margin: 0;
  border-radius: 0.3rem;
  border-color: #cfd3d5;
  text-align: center;
  background-color: white;
  color: #6e7c84;
  font-size: 1.3rem;
  border-left-color: #cfd3d5 !important;
  border-top-color: #cfd3d5;
}
.count > input[type="number"]::-webkit-outer-spin-button,
.count > input[type="number"]::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
  margin: 0;
}

.count > input[type="number"] {
  -moz-appearance: textfield;
}

.count button {
  width: 2.2rem;
  height: 2.2rem;
  padding: 0;
  margin: 0;
  border-radius: 0.3rem;
  background-color: #e9ebec;
  color: #707070;
  font-size: 1.7rem;
  line-height: 0;
  text-decoration: none;
}

  <button id="down" on:click={decreaseBtn}>-</button>
  <input
    id="numericUpDown"
    class="count-input"
    type="number"
    value={qty}
  />
  <button id="up" on:click={increaseBtn}>+</button>

A: Поменяйте значение   ⠀border-left-color и
border-top-color ⠀у класса  count-input

.count {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 0.1rem;
}

.count-input {
  width: 2.2rem;
  height: 2.2rem;
  margin: 0;
  border-radius: 0.3rem;
  border-color: #cfd3d5;
  text-align: center;
  background-color: white;
  color: #6e7c84;
  font-size: 1.3rem;
  border-left-color: red; /********* Левая граница **********/
  border-top-color: blue; /******** Верхняя граница *********/
}
.count > input[type="number"]::-webkit-outer-spin-button,
.count > input[type="number"]::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
  margin: 0;
}

.count > input[type="number"] {
  -moz-appearance: textfield;
}

.count button {
  width: 2.2rem;
  height: 2.2rem;
  padding: 0;
  margin: 0;
  border-radius: 0.3rem;
  background-color: #e9ebec;
  color: #707070;
  font-size: 1.7rem;
  line-height: 0;
  text-decoration: none;
}

  <button id="down" on:click={decreaseBtn}>-</button>
  <input
    id="numericUpDown"
    class="count-input"
    type="number"
    value={qty}
  />
  <button id="up" on:click={increaseBtn}>+</button>


text: Q: Why do forms and menus need two windows? The manpages menu_win(3X) and form_win(3X) say that the main window (set with set_menu_win(MENU*, WINDOW*) in menus) displays any title and border associated with the window. Why is this necessary? Wouldn't be one window for the actual forms/menus enough or does it have some purpose?


text:
Q: Could not load file or assembly 'MySql.Data, Version=6.3.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' or one of its dependencies How to resolve this issue
Could not load file or assembly 'MySql.Data, Version=6.3.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
The site is running good in local host but when publishing the site and checking i am getting the error. Can any one give me a solution for this..
My sample image from Assembly folder

A: The DLL either needs to be in the bin folder of the application (or in the same folder) or needs to be installed to the GAC.
Does the MySql DLL come with an installer?
--
This can also happen when the referenced DLL is built with a later version of .Net than the application that is calling it.


text:
Q: nullPointerException and how to update label the right way? I have 2 scenes :
The first one has a "Balance" Label, which displays the balance from a variable.
The second scene is the deposit scene where the user adds to the balance.
(Each scene has its controller class)
I want the balance to be updated when the user goes back to the first scene.
what's the best way to do so? I couldn't find an event for the scene shown, I found online only a stage example which triggers an event when the window is closed, but here I am just changing scenes by changing the mainstage scene.
I have tried making an object of the first scene class inside the second scene's class and calling a method to change the label text when I click the back button but that didn't work.
Here's the code for the first scene where lbBalance is the label I want to update, and updateBal is the method I am using in the second scene class.
public class accountController extends Controller implements Initializable {

    @FXML private Label gilbert;
    @FXML private Label lbBalance;
    @FXML private Button deposit;
    @FXML private Button btn_showBalance;
    private application.depositController depositController;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        lbBalance.setText(String.valueOf(BAL));
    }

    @FXML
    public void handleDeposit(ActionEvent event) throws IOException {
        Parent depositParent = FXMLLoader.load(getClass().getResource("deposit.fxml"));
        depositScene = new Scene(depositParent);
        mainStage.setScene(depositScene);
        mainStage.show();
    }

    public void updateBal() {
        lbBalance.setText(String.valueOf(BAL));
    }

}

Here's the second scene's class
accountController backtoscene= new accountController();
@FXML private Label info;
@FXML private Button btn_depositfinal;
@FXML private TextField depositamount;
@FXML private Button btn_back;

public void initialize(URL location, ResourceBundle resources) {
    // TODO Auto-generated method stub
}

@FXML
public void handleDepositFinal(ActionEvent event) {
    deposit(Integer.parseInt(depositamount.getText()));
    info.setVisible(true);
}

@FXML
public void handleBackButton(ActionEvent event) throws IOException {
    backtoscene.updateBal();
    mainStage.setScene(newscene);

}

TL;DR calling the method is giving me a nullPointerException, is there any other way to update the balance label when getting back to previous scene?

A: NOTE: I haven't tested the code, I just wrote it freehand, but it gives you a general idea.
Your main issue is that you are creating a new AccountController in the DepositController. Meaning it's a different one than the one you originally instantiated.
public class AccountController extends Controller implements Initializable {

    @FXML private Label gilbert;
    @FXML private Label lbBalance;
    @FXML private Button deposit;
    @FXML private Button btn_showBalance;
    private application.DepositController depositController;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        lbBalance.setText(String.valueOf(BAL));
    }

    @FXML
    public void handleDeposit(ActionEvent event) throws IOException {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("deposit.fxml"));
        Parent depositParent = loader.load();
        depositScene = new Scene(depositParent);
        depositController = loader.getController();
        depositController .setAccountController(this);

        mainStage.setScene(depositScene);
        mainStage.show();
    }

    public void updateBal() {
        lbBalance.setText(String.valueOf(BAL));
    }

}

Here's the second class where you need to set the AccountController to be the one you originally initialized :
public class DepositController extends Controller implements Initializable {
    AccountController backtoscene;
    @FXML private Label info;
    @FXML private Button btn_depositfinal;
    @FXML private TextField depositamount;
    @FXML private Button btn_back;

    public void initialize(URL location, ResourceBundle resources) {
        // TODO Auto-generated method stub
    }
    public void setAccountController(AccountController controller){
        backtoscene = controller;
    }

    @FXML
    public void handleDepositFinal(ActionEvent event) {
        deposit(Integer.parseInt(depositamount.getText()));
        info.setVisible(true);
    }

    @FXML
    public void handleBackButton(ActionEvent event) throws IOException {
        backtoscene.updateBal();
        mainStage.setScene(newscene);

    }
}

Now you have access to the AccountController you originally initialized at the start, and the AccountController has access to the correct DepositController.


text:
Q: In Outlook, I cannot jump to the meeting out of the "Decline" response When I get a "Decline" from a meeting participant, I want to open the meeting itself quickly. Normally there is a button to achieve this, but it is greyed out:
(below the menu, in the "Respond" group, at the top of the rightmost column)

What can I do to make it visible? What can I ask the admin to change?

A: Is the button your mentioned just like the folloing screenshot?

This button means "Reply with Meeting", When you receive an email message or a task request, you can create a meeting request as a response with one click.
For more information, see: Respond to an email message with a meeting request
So, when you receive a meeting response message, that button is not available.


text:
Q: holding data in a form in asp.net I have a simple inquiry form which includes first name,last name etc....first i inserted the records in it but when i click in the submit button it says you have to log in first to submit the query.so i logged in to the website and i need that data which i inserted first time in the website that is in the inquiry form.....how to keep on holding that data???.....so that i need not write it again.
here is my code below:
protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            if (Session["userid"] != null)
            {
                if (FileUpload1.HasFile)
                {
                    string str = FileUpload1.FileName;
                    FileUpload1.PostedFile.SaveAs(Server.MapPath(".") + "//images//" + str);
                    string path = "~//images//" + str.ToString();
                    con.Open();
                    con.Close();
                    Label1.Text = "File uploaded successfully";
                    main addinfo = new main();
                    string Id = Request.QueryString["id"];
                    string SQL = "insert into mandir(user_id,name,place,description,with_religion_category,with_district,with_religion,photo)values('" + Session["userid"] + "','" + txttemplename.Text.Trim() + "','" + txtaddress.Text.Trim() + "','" + txtdescription.Value + "','" + ddlreligioncategory.SelectedItem.Value + "','" + ddlreligion.SelectedItem.Value + "','" + ddldistrict.SelectedItem.Value + "','" + path + "')";
                    addinfo.saveData(SQL);
                    txttemplename.Text = "";
                    txtaddress.Text = "";
                    txtdescription.Value = "";
                    lblenquirymsg.Text = "Thank you for providing the information";
                }
                else
                {
                    Label1.Text = "File not uploaded successfully";
                }
            }

            else
            {
                lblinfo.Text = "You Must Login Or Register To give information";

            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("{0} Exception caught.", ex);
        }
    }
}

A: You might want to use sessions for it. Sessions make use of cookies, which are stored in the client. I've personally used this approach and it works perfectly for my needs :) A sample of this is...
Session["whatevername"]=username;

And if you want to retrieve data from this value, like if the session ID is still in used, then...
if (Session["whatevername"]!=null)
{
  //Whatever you want to do...
}

In addition to this... Another way to do this is to save the values as cookies directly... Say you just pressed the login button... Add this code under button click event...
HttpCookie cookie = new HttpCookie("cookieid");
cookie.Values.Add("Username", Username.Text);
cookie.Values.Add("Password", Password.Text);

Upon reloading of form... Instead of entering credentials again, you make a code that detects if there are cookies like this...Put this under load event...
if (HttpContext.Current.Request.Cookies["cookieid"] != null)
{
    Username.Text = HttpContext.Current.Request.Cookies["cookieid"]["Username"].ToString();
    Password.Text = HttpContext.Current.Request.Cookies["cookieid"]["Password"].ToString();
}

A: You need to create session variables when the login is successful. For instance:
Session["userid"] = username;

Since your code checks for a session with "userid" as the value. username should be the textbox value you inserted.


text:
Q: Deselect selected listitem in xamarin forms for Win 8.1 I have a page with a listview, when you press the row it takes you to a detail page. When you navigate back you should get the same list without a selected item. If I don't set the selectedItem to null, you can't select the same row again. Setting the SelectedItem to null works as expected on Android and iOS, but it throws an exception on WP 8.1.
My code:
async Task OnSelection (object sender, SelectedItemChangedEventArgs e)
    {
        var list = ((ListView)sender);
        if (e.SelectedItem == null) {
            return;
        }
        var sessionViewModel = e.SelectedItem as SessionViewModel;
        list.SelectedItem = null;
        await Navigation.PushAsync(new AgendaDetail(sessionViewModel));
    }

The exception:
System.ArgumentException: Value does not fall within the expected range.
at Windows.UI.Xaml.Controls.Primitives.Selector.put_SelectedIndex(Int32 value)
at Xamarin.Forms.Platform.WinRT.ListViewRenderer.OnElementItemSelected(Object sender,
SelectedItemChangedEventArgs e)

Is there another way to clear selected item on WinPhone 8.1?


text:
Q: aspx.net newbie: how to implement an Ajax clock and stopwatch? Im trying to create two textboxes: one containing a simple clock and other containing a kind of stopwatch. I'm using a ScriptManager, a UpdatePannel and a Timer. But, this script is running on server, generating postbacks (I think), using bandwith and processing on server side. How can I implement this task using browser processing (like writting a java script on the page code)? - Later I'm going to store the stopwatch datum in database.

A: Ok, I found the answer in: http://wiki.asp.net/page.aspx/280/javascript-to-display-time-on-web-page/
<script type="text/javascript">

    function ShowTime() {

        var dt = new Date();

        document.getElementById("<%= TextBox1.ClientID %>").value = dt.toLocaleTimeString();

        window.setTimeout("ShowTime()", 1000);

    }

</script>

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<script type="text/javascript">

    // a startup script to put everything in motion

    window.setTimeout("ShowTime()", 1000);

</script>


text:
Q: Let $G$ be a group. Show that, for every $a\in G$, the map $\phi_a:G\to G$, defined by $\phi_a(g) := aga^{−1}$ ($g\in G$), is a group automorphism. Let $G$ be a group. Show that, for every $a \in G$, the map $\phi_a : G \to G$, defined by $\phi_a(g) := aga^{−1}~ (g \in G)$, is a group automorphism.
Don't really understand how exactly to go about this one - do I have to show that $ϕa$ is a homomorphism and then bijective?

A:
do I have to show that $G$ is a homomorphism and then bijective?

I assume that was a typo and you meant "$\phi_a$ is a homomorphism and then bijective". Yes, that's what you need to show.
Proof.

*

*$\phi_a$ is a homomorphism: Indeed, let $g,h\in G$ and $e\in G$ be the neutral element. Then $$\phi_a(gh)=agha^{-1}=ageha^{-1}=aga^{-1}aha^{-1}=\phi_a(g)\phi_a(h)$$

*$\phi_a$ is bijective: It is enough to construct the inverse of $\phi_a$. So consider $\phi_{a^{-1}}$. Then we have $$\phi_a\big(\phi_{a^{-1}}(x)\big)=\phi_a(a^{-1}xa)=aa^{-1}xaa^{-1}=x$$
Analogously $\phi_{a^{-1}}\big(\phi_a(x)\big)=x$. Therefore $\phi_{a^{-1}}$ is the inverse of $\phi_a$ which completes the proof. $\Box$

A: Yes, that's what you must show. By definition, an automorphism is an isomorphism from a group to itself- it is, therefore, a permutation of its elements. So, for example, $\phi _a$ is an automorphism because: i) it is a homomorphism; ii) it is a permutation of the elements of $G$. There are many ways of proving these things, but, if you're just a begginer, I'd recommend to do it more sistematically.

I'll give an example of how you could do it sistematically- if you want to answer the question by yourself, there's no need to read this. As an example, to prove it is a homomorphism, just show that, if $b,c\in G$,
$$\phi _a(bc)=abca^{-1}=aba^{-1}aca^{-1}=\phi _a(b) \phi _a (c).$$ To prove it is a bijection, show it is injective and surjective. To show the first part, let $\phi _a(b)=\phi _a(c).$ Therefore, $aba^{-1}=aca^{-1}$, so that $b=c$. To show it is surjective, let $y=a^{-1}ba$. Therefore, $\phi_a(y)=b$, so that our funciont is surjective.


text:
Q: {{link}} is getting returned while scraping URLs from a webpage using Python I am scraping urls from a webpage like below
from bs4 import BeautifulSoup
import requests

url = "https://www.investing.com/search/?q=Axon&tab=news"
response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
soup = BeautifulSoup(response.content, "html.parser")

for s in soup.find_all('div',{'class':'articleItem'}):

    for a in s.find_all('div',{'class':'textDiv'}):
        for b in a.find_all('a',{'class':'title'}):
            print(b.get('href'))

And the output is coming like below
/news/stock-market-news/axovant-updates-on-parkinsons-candidate-axolentipd-1713474
/news/stock-market-news/digital-alley-up-24-on-axon-withdrawal-from-patent-challenge-1728115
/news/stock-market-news/axovant-sciences-misses-by-009-763209
/analysis/microns-mu-shares-gain-on-q3-earnings-beat-upbeat-guidance-200529289
/analysis/axon,-espr,-momo,-zyne-200182141
/analysis/factors-likely-to-impact-axon-enterprises-aaxn-q4-earnings-200391393
{{link}}
{{link}}

The problem is

*

*All the URLs are not getting extracted

*See the last two entries,Why is it so ?

Any solution to the above two problems ?

A: That's because you are making a HTTP request, while youtube renders the video data using JavaScript. To be able to parse to soup the JS content, you have to use the library which supports making requests and then rendering it with JS. Try to use the module requests_html. pypi.org/project/requests-html

A: One way to get around this problem is with selenium:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

And when selenium have scrolled down to the bottom of the page you read the pagesource and close selenium and parse pagesource with Beautifulsoup. You can also parse with selenium to.
First selenium and bs4:
from selenium import webdriver
from bs4 import BeautifulSoup

import time

PAUSE_TIME = 1
driver = webdriver.Firefox(executable_path='c:/program/geckodriver.exe')
driver.get('https://www.investing.com/search/?q=Axon&tab=news')
lh = driver.execute_script("return document.body.scrollHeight")

while True:

    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

    time.sleep(PAUSE_TIME)

    nh = driver.execute_script("return document.body.scrollHeight")
    if nh == lh:
        break
    lh = nh
pagesourece = driver.page_source
driver.close()

soup = BeautifulSoup(pagesourece, "html.parser")

for s in soup.find_all('div',{'class':'articleItem'}):

    for a in s.find_all('div',{'class':'textDiv'}):
        for b in a.find_all('a',{'class':'title'}):
            print(b.get('href'))

And selenium only version:
from selenium import webdriver
from bs4 import BeautifulSoup

import time

PAUSE_TIME = 1
driver = webdriver.Firefox(executable_path='c:/program/geckodriver.exe')
driver.get('https://www.investing.com/search/?q=Axon&tab=news')
lh = driver.execute_script("return document.body.scrollHeight")

while True:

    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

    time.sleep(PAUSE_TIME)

    nh = driver.execute_script("return document.body.scrollHeight")
    if nh == lh:
        break
    lh = nh
pagesourece = driver.page_source

for s in driver.find_elements_by_css_selector('div.articleItem'):

    for a in s.find_elements_by_css_selector('div.textDiv'):
        for b in a.find_elements_by_css_selector('a.title'):
            print(b.get_attribute('href'))
driver.close()

Note tou have to install selenium and download geckodriver to rund this. If you want to have geckodriver in an other path then c:/program you have to change:
driver = webdriver.Firefox(executable_path='c:/program/geckodriver.exe')

to your geckodriver path.


text:
Q: Publishing and debugging Microsoft Bot Service I have developed a bot that works perfectly on my local machine and accessible through all channels via ngrok.
However, the Bot doesn't work on its deployed Azure url which is https://mybot.azurewebsites.com/api/messages A test with the webchat or bot emulator returns an error 500 without further information on exact cause of the issue. How would I debug so that I can find out more information on what's causing the breakdown?


text:
Q: Delay textChanged Event Xamarin forms I learning Xamarin, I would like to wait a user to finish to tap on the searchbar then do something. I want to use TextChange to make it dynamic
Here is my Xaml  Search code :
 <!--THe search bar-->
<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand"  VerticalOptions="FillAndExpand" >
<SearchBar  x:Name="VariableSearchWords"    TextChanged="SearcNews">  </SearchBar>
 </StackLayout>
<!--END THe search bar-->

Here is the function:
   public async void GetNewsData(string title, string Mylanguage)
    {

        newsObj= new List<NewsModel>();
            var client = new NewsSearchClient(new ApiKeyServiceClientCredentials(key));
            var newsResults = client.News.SearchAsync(query: searchTerm, market: Mylanguage, count: 14, originalImage: true).Result;
            if (newsResults.Value.Count > 0)
            {

                for (int i = 0; i < newsResults.Value.Count; i++)
                {
                         var news = new NewsModel();

                        news.NewsUrl = newsResults.Value[i].Url;
                        news.NewsImageUrl = await DownloadImagesAsync(newsResults.Value[i].Image.ContentUrl);
                        newsObj.Add(news);

                    }

                }

                NewsList.ItemsSource = newsObj;
                // return newsObj;
            }

    }

// search for words
  private async void SearcNews(object sender, TextChangedEventArgs e)
    {

        // StaRT what you want to do after 200 millisecond delay

        NewsList.ItemsSource = null;

        if (task == null)// very
        {
            task = Task.Run(async () =>
            {
                await Task.Delay(timeDelay);

               //get data
               GetNewsData("  ", myuser.NewsLanguage); //getData

                // END what you want to do after 200 millisecond delay
                task = null;
            });
        }
    }

Thanks for your help

A: You could use Task to achieve this effect,check below :
 <SearchBar x:Name="VariableSearchWords" Placeholder="hi" TextChanged="SearcNews"></SearchBar >

 Task task;
 int timeDelay = 1000;
 private async void SearcNews(object sender, TextChangedEventArgs e)
    {
        if (task == null || task.IsCompleted)
        {
            task = Task.Run(async () =>
            {
                await Task.Delay(timeDelay);
                FunctionThatDoesSomethingAfter(VariableSearchWords.Text);// what you want to do after 200 millisecond delay
            });
        }

    }


text:
Q: How can I get a DateTime corresponding to next occurence of hour, minute? I'd like to be able to get a correct DateTime for the NEXT occurrence of a time that I can specify with just an hour and minute. I'd also like to be able to do this by specifying the same thing for that hour and minute, but for the next occurrence of that on (say) a Wednesday.
Also, note that if the current minute has already "started" (which I guess means that we're in 00 milliseconds of that minute) then, again, we need to find the "next" occurrence of that time.
An example with (say) getting a DateTime for the next 10:34 AM and next 12:45 PM that's on a Wednesday, would be greatly appreciated.
How can I do this in Joda?

A: Something like this, for "next 10:34 AM on a Wednesday:"
DateTime getNextTimeOnDay(int dayOfWeek, int hourOfDay, int minuteOfHour)
{
    DateTime now = new DateTime();
    DateTime then = now
        .withDayOfWeek(dayOfWeek)
        .withHourOfDay(hourOfDay)
        .withMinuteOfHour(minuteOfHour)
        .withSecondOfMinute(0)
        .withMillisOfSecond(0);

    return then.isBefore(now) ? then.plusWeeks(1) : then;
}

DateTime nextWednesdayAtTenThirtyFour
    = getNextTimeOnDay(DateTimeConstants.WEDNESDAY, 10, 34);

// as of now, this is 2012-01-06T10:34:00.000-05:00

A: java.time
The Answer by Matt Ball is correct for Joda-Time. The makers of Joda-Time have said we should move to the java.time framework built into Java 8 and later as soon as is convenient. So here is the same kind of code rewritten for java.time.
DayOfWeek enum
Since java.time is built into Java, it seems reasonable to replace the argument using an int as the day-of-week with the bundled enum DayOfWeek.
Time Zone
The code in the other Answer has one major issue: It depends implicitly on the JVM's current default time zone. That default can change at any moment, even during runtime(!). Better to always specify the expected/desired time zone. So I added another argument to our method.
DST Adjustment
If your specified hour and minute land in an anomaly such as Daylight Saving Time (DST), java.time will make an adjustment. Be sure to read the doc to understand that behavior and verify it meets with your desires/expectations.
Using a TemporalAdjustor of next( dayOfWeek ) defined in TemporalAdjustors (notice the plural s) means we will get the next such day, going forward in the future and never the past. So we can drop the ternary test in the return statement.
public ZonedDateTime getNextTimeOnDay ( ZoneId zoneId, DayOfWeek dayOfWeek, int hourOfDay, int minuteOfHour ) {
    ZonedDateTime now = ZonedDateTime.now ( zoneId );
    ZonedDateTime then = now
            .with ( TemporalAdjusters.next ( dayOfWeek ) )
            .withHour ( hourOfDay )
            .withMinute ( minuteOfHour )
            .withSecond ( 0 )
            .withNano ( 0 );

    return then;
}

An example calling that method.
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime nextWednesdayAtTenThirtyFour = this.getNextTimeOnDay ( zoneId, DayOfWeek.WEDNESDAY, 10, 34 );

Dump to console.
System.out.println ( nextWednesdayAtTenThirtyFour );

2016-01-20T10:34-05:00[America/Montreal]

By the way, you may want to pass a ZonedDateTime to be used by the method as the starting point rather than assume "now". This route might be more useful/flexible and facilitate testing. If you choose this route, no need to pass the ZoneId as the passed ZonedDateTime carries with it the assigned time zone.


text:
Q: Modal Registration Box using ExpressionEnine and jQuery I'd like to create a modal style registration/login box for my ExpressionEngine site.  What's the best way to handle registration on a modal box?  Should I call a registration page using an iframe.  Are there security concerns?

A: You can try cloning the following html that you have on your main login page into the modal box:
<form method="post" action="/">

                X
                <input type="hidden" name="RET" value="-1">

            Username
            <input type="text" class="input" id="username" name="username" size="15" value="">
            <input type="hidden" name="auto_login" value="1">

            Password
            <input type="password" class="input" name="password" size="15">

                    Forgot your password?
                    <input type="submit" class="submit" value="Login">

        </form>

A: I use fancybox. Call it as an iframe and just make sure you post it to the appropriate template/page, which you will set in the return="" parameter, and if it is set as an iframe, it will post to that page still within the modal window (fancybox).


text:
Q: How do I background a systemd-nspawn container? I use systemd-nspawn to run a few containers. I can have them started in the background using systemctl start systemd-nspawn@foo. On occasion, however, I start with systemd-nspawn -bD foo. I couldn't find any way to send it to the background. Closing the terminal just kills the container as machinectl list shows. Can I do so, and if so, how?
I understand a container is much more than a single process, but in this sense, the expected effect is the same as backgrounding a process - I want the container running, but my original shell given back to me.

A: Ok, so, for what it's worth, the following was successful for me:
sudo systemd-nspawn -bxD/

Practically identical to yours, except I don't give the machine a name and I get an -x ephemeral btrfs snapshot of my / for the container's root.
That brought up the container's getty on my terminal's pty and I logged in to login and all.
I confess I was a bit stumped for a little while, but after a little poking at systemctl in the container w/ zsh <tab> completion I came up with (run from within the container):
systemctl stop console-getty.service

==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ===
Authentication is required to manage system services or other units.
Authenticating as: mikeserv
Password:
==== AUTHENTICATION COMPLETE ===

Which got the machine to surrender its terminal control. The only thing is, I started that with sudo - which also gets its own layer of terminal control to authenticate in the first place. This left me with a blank terminal, and no amount of kill -CONT "$(pgrep ksh)" was doing me any good. And so I was again stumped for a moment or two, but (in another terminal)...
sudo fuser -v /dev/pts/*

                     USER        PID ACCESS COMMAND
/dev/pts/0:          mikeserv   8347 F.... zsh
                     root      18003 F.... sudo
/dev/pts/13:         mikeserv   9553 F.... zsh
                     mikeserv  16838 F.... ksh
                     root      17657 F.... sudo
                     root      17658 F.... systemd-nspawn
/dev/pts/14:         root      17675 F.... systemd

Gave me the above list, and so I thought - what the hell?
sudo kill -STOP 17657

And - lo and behold - I had ksh back in the original terminal. To wrap it up, I needed to verify I could still access the machine, though, of course, else it would be useless:
machinectl -l

MACHINE                    CLASS     SERVICE
localhost-35ceaa76b1306897 container nspawn

Ok...
sudo machinectl login localhost-35ceaa76b1306897

Connected to machine localhost-35ceaa76b1306897.
Press ^] three times within 1s to exit session.

Arch Linux 4.0.7-2-ARCH (pts/0)

localhost-35ceaa76b1306897 login:

And I got another getty on another terminal!

A: I have a similar issue. My approach is to use dtach to control attaching and detaching from the terminal that is running the container. Then inside the container I can run tmux / screen etc.
machinectl will allow you to run containers at boot, but as of this writing, debian stable does not have a version of systemd that includes this feature.


text:
Q: Delete specific line from text file I want to have a method that will take the file path and then delete a specific line from a text file and this is the code I came up with.
Method.java
public class Method {
static void deletefileline(String file, Integer line) throws IOException {
    ArrayList<String> filecontent = new ArrayList<String>();
    try {
        File myObj = new File(file);
        Scanner myReader = new Scanner(myObj);
        while (myReader.hasNextLine()) {
            String data = myReader.nextLine();
            filecontent.add(data);
        }
        myReader.close();
    } catch (FileNotFoundException e) {
        System.out.println("An error occurred.");
        e.printStackTrace();
    }
    File f = new File(file);
    f.delete();
    filecontent.remove(line);
    try {
        File newfile = new File(file);
        newfile.createNewFile();
    } catch (IOException e) {
        System.out.println("An Error Occured");
    }
    for (Integer i = 0; i < filecontent.size(); i++) {
        String textToAppend = "\r\n" + filecontent.get(i);
        Path path = Paths.get(file);
        Files.write(path, textToAppend.getBytes(), StandardOpenOption.APPEND);
    }
}

public static void main(String[] args) {
    deletefileline("src/test.txt", 1);
 }
}

This is the text file
test.txt
hi
hello
hii
helloo

This is the text file after i ran Methods.java
Output:
hi
hello
hii
helloo

It won't show it but at the first "hi" before that there is a space so it only added a space at line 1.
So the problem is that when it is running it only adds an extra line at line 1.

A: Why is not the line removed?
https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

*

*E remove(int index) Removes the element at the specified position in this list.

*boolean remove(Object o) Removes the first occurrence of the specified element from this list, if it is present.

Since Integer line is Object and not a primitive data type int, this call
filecontent.remove(line);

tries to remove the line with a content equal to new Integer(1).
Change the method argument to int line or add type cast to the call filecontent.remove((int) line).
Why is an empty line added?
The extra space is added by this statement:
String textToAppend = "\r\n" + filecontent.get(i);

Change it like this:
String textToAppend = filecontent.get(i) + "\r\n";

A: This is a small snippet to perform same function as mentioned in question (kotlin version, however same can be done in java)
import java.io.File
class RemoveFileContent {
    fun deleteContentAtIndex(filePath: String, indexPos: Int) {
        val bufferedWriter = File("/SampleOutputFile.txt").bufferedWriter()
        File(filePath).readLines().filterIndexed { i, _ -> i != indexPos }.forEach {
            bufferedWriter.appendLine(it)
        }
        bufferedWriter.flush()
    }
}
fun main(args : Array<String>) {
    RemoveFileContent().deleteContentAtIndex("/SampleFile.txt",2)
}

Input :             Output:
    hi                  hi
    hello               hello
    hii                 helloo
    helloo

Disclaimer : Note that if your file content are huge, this can lead to high memory consumption, as stated here - How to remove first line of a text file in java


text:
Q: regex for email address list that may span multiple lines I want to scan the body of an email for email address lists from forwarded emails, like:
From: John Smith <john@example.com>
To: Jane Smith <jane@example.com>, Mary Smith
<mary@example.com>
Cc: Ed Smith <ed@example.com>
Subject: this is a test

I'm going to use Mail_RFC822::parseAddressList() to fully parse each list (there are a lot of details to get right in there, so I shouldn't try to re-engineer it), but I do want to pluck out the lines to hand off to this function.  I have a simple regex that just looks for lines with email addresses, and that works most of the time.
But in the wild, there are sometimes emails like the example above, where the name and address get split onto different lines.  If I do it line by line, the top half of the To: line above will fail to parse at all in parseAddressList() because a name without an address is invalid; and the bottom half will parse, but will be missing the name, which was on the previous line.
So I need a regex that can look at multiple lines at once, which complicates things beyond my expertise.  An adequate solution would continue to group lines together as long as it keeps finding a basic email pattern ([\w\.\+\-]+@[\w\.\-]+\.[\w\.\-]+ ... doesn't need to be perfect) but without a word-colon combo at the beginning of the line (^\S*:) so that, as in the example above, the Cc: line is a separate match.  Thanks in advance for your help.

A: You can pre-process the string to remove new lines before < characters and then pass the result to your parseAddressList function.
Something like replacing /(?:\r?\n|\r)\s*</ with <:
$emails = Mail_RFC822::parseAddressList(preg_replace('/(?:\r?\n|\r)\s*</', '<', $emailHeaders));

A: How about using the regex s operator, so that . matches newline characters too: /your regex/s ?


text:
Q: How to find cardinality of $C \backslash (B \cup D)$? Let $B, C, D$ be finite sets $|B|=|C|  $ where $|\cdot|$ is the cardinality of the set.
Show that
$$
|C \backslash (B \cup D)|=|B \backslash C| -|(C \cap D) \backslash B|
$$
where $\backslash$ is the set difference.

A: As pointed out by Zuy in the comment, I only have a proof for the case that $B$ and $C$ are finite sets:
By $|B|=|C|$, we have $|B\setminus C|=|C\setminus B|$.
Also, $C\setminus B$ is the disjoint union of $C\setminus (B\cup D)$ and $(C\cap D)\setminus B$. Thus, we have
$$|B\setminus C|=|C\setminus (B\cup D)|+|C\cap D)\setminus B|.$$
It has nothing to do with $|D|\leq |B|$.

In general, the equality can be disproved with $C=\mathbb{Z}$ and $B=D=\mathbb{Z}^+$:
We have

*

*$|B\setminus C|=|\mathbb{Z}^+\setminus \mathbb{Z}|=|\varnothing|=0$,

*$|C\setminus (B\cup D)|=|\mathbb{Z}\setminus \mathbb{Z}^+|=|\{0\}\cup \mathbb{Z}^-|=\aleph_0$, and

*$|(C\cap D)\setminus B|=|\mathbb{Z}^+\setminus \mathbb{Z}^+|=|\varnothing|=0$.

A: This is wrong in general. If $C$ is a strict subset of $B$ (for instance $B=\mathbb N$ and $C=\mathbb N_{>0}$), the left side equals $0$, while the right one is strictly greater than $0$.

A: The first step is to observe that the sets $C\setminus (B\cup D)$ and $(C\cap D)\setminus B$ form a partition of $C\setminus B$.
We know, then, that $\bigl|C\setminus (B\cup D)\bigr| = |C\setminus B| - \bigl|(C\cap D)\setminus B\bigr|$.
It suffices, therefore, to prove that $|C\setminus B| = |B\setminus C|$, which follows from $|B|=|C|$. The fact that $|D|\leq|B|$ seems useless.


text:
Q: Error bar in python plot
HI! I have this code in python
plt.errorbar(W50DM,VmaxDM,W50DM_std, fmt='r^')
plt.semilogy()
plt.semilogx()
plt.axis([10, 1000, 1, 1000])
plt.xlabel("VmaxDM")
plt.ylabel("W50DM")
plt.show()

W50DM_std contains the standard deviations for W50DM. The problems is that the elements of W50DM_std are all bigger than 0, usually bigger than 10, but as you can see in the plot there are some points with no standard deviation. Do you know why this is happening?


text:
Q: How to insert Xml element at a specific location using LINQ? Here is my XML,

      <C name="A" />
      <C name="B" />
      <C name="C" />
      <C name="G" />

I need to insert another tag after the last <C> tag and output should like ,

      <C name="A" />
      <C name="B" />
      <C name="C" />
      <C name="G" />
      <D name ="New Tag" >
        <E />
      </D>

Using following C#,
doc.XPathSelectElement("A/B/C[last()]").?// Unable to proceed on what operation to make here
I'm trying with c# LINQ Insert/Add methods :(
Any Help Appreciated!

A: Use doc.XPathSelectElement("A/B/C[last()]").AddAfterSelf(new XElement("D", new XAttribute("name","New Tag"),new XElement("E")));

A:
You are going in right direction with doc.XPathSelectElement
  Further try using XElement.AddAfterSelf, it will help you to add the specified content immediately after a node.
  See the link for more details.

Original Link


text:
Q: Text Box Button to update Ajax table (JS) there is a comment button, that opens a text box in a table on my website. I'm looking to have this "comment" box update the "comment" column in my ajax table, without having to go into the table individually and edit each input.
Here is the comment text box:
'"columns": [
                  /* Name of the keys from
                  data file source */
                  { "data": "TABLE_SCHEMA" },
                  {
                    "data": "TABLE_NAME",
                    "render": function(data, type, row, meta){
                            return data;
                        }
                  },
                  { "data": "COLUMN_NAME" },

                  { "data": "COMMENT",
                    "render": function(data, type, full){
                        const myArray = data.split('|');
                        var setdiv = "
<textarea id='txt_"+myArray[0]+"'></textarea>
";
                        var ret = '<input name="cmt[]" type="button" onclick="trigrbtn(\''+myArray[0]+'\', \'example text\');" value="Comment">';
                        ret += setdiv;
                        return ret;
                        PDOHist($talon_schema, $tid)
                        //<div id='poptxt_{ID}'
                    }
                }
              ],'

Here is the code for the ajax table:
`include_once("../../functions/sql_func.php") ;
$sql = "SELECT TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME,DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS ORDER BY TABLE_SCHEMA";
$seldta = SQLRes($sql);

$i = 0;
while($row = mysqli_fetch_array($seldta)) {
  $sql1 = "SELECT com AS cnt FROM shared.Talon_schema
  WHERE db = $row[TABLE_SCHEMA]
  AND tbl = $row[TABLE_NAME]
  AND col = $row[COLUMN_NAME]";
  $selcom = SQLRes($sql1);
  $com = mysqli_fetch_array($selcom);
    $dataTable .= '{';
        $dataTable .= '"TABLE_SCHEMA": "'.$row[TABLE_SCHEMA].'",';
        $dataTable .= '"TABLE_NAME": "'.$row[TABLE_NAME].'",';
        $dataTable .= '"COLUMN_NAME": "'.$row[COLUMN_NAME].'",';
        $dataTable .= '"COMMENT": "'.$i.'|'.$com[com].'"';
    $dataTable .= '},';
    $i++;
  }
  $dataTable = substr_replace($dataTable ,"",-1);
  echo $dataTable;`