text:
Q: Optimize Bulk insert performance in sqlite iphone I am trying to save more than 500 records at once in sqlite, code that I have wrote so far is given below
The method name closeDatabase closes any open connection of the database the variable ContactID is nothing but an Array which is populated with ContactID of people present in my address book.

 sqlite3_exec(databaseRefObj, "BEGIN TRANSACTION", 0, 0, 0);

                for (NSString *contactIDstr in contactID)
                {
                    const char *insertintoGropsMember = "My insert query here";
                    NSString *groupIDstr = [NSString stringWithFormat:@"%d",grpID];

                    [self closeDatabase];

                    if(sqlite3_prepare_v2(databaseRefObj, insertintoGropsMember, -1, &sqlstatement, NULL)==SQLITE_OK)
                    {
                        sqlite3_bind_text(sqlstatement, 1, [groupIDstr UTF8String], -1, SQLITE_TRANSIENT);
                        sqlite3_bind_text(sqlstatement, 2, [contactIDstr UTF8String], -1, SQLITE_TRANSIENT);
                        sqlite3_step(sqlstatement);
                    }
                    else
                    {
                        successFlag = NO;
                    }

                    sqlite3_finalize(sqlstatement);
                    sqlite3_close(databaseRefObj);
                }

                sqlite3_exec(databaseRefObj, "END TRANSACTION", 0, 0, 0);

The process of data insertion is quite slow here and I would like to know where am I going wrong or what steps should I follow to optimize my sqlite performance.
Please note that I am not using any kind of index on the column on which I want to perform the insert.

A: I can see several issues with your code:

*

*You appear to be closing the database during processing.

*You aren't taking advantage of the statement prepare/multiple binding capability.

*You are binding the integers as text, when sqlite3 will happily bind integer values

Try this code:
BOOL ok = YES;
sqlite3_exec(databaseRefObj, "BEGIN TRANSACTION", 0, 0, 0);
const char *insertintoGropsMember = "My insert query here";
if (sqlite3_prepare_v2(databaseRefObj, insertintoGropsMember, -1, &sqlstatement, NULL) == SQLITE_OK)
{
    for (NSString *contactIDstr in contactID)
    {
        sqlite3_bind_int(sqlstatement, 1, grpID);
        sqlite3_bind_text(sqlstatement, 2, [contactIDstr UTF8String], -1, 0);
        if (sqlite3_step(sqlstatement) != SQLITE_DONE)
        {
            NSLog(@"Error inserting row: %s", sqlite3_errmsg(databaseRefObj));
            ok = NO;
            break;
        }
        sqlite3_reset(sqlstatement);
    }
    sqlite3_finalize(sqlstatement);

    sqlite3_exec(databaseRefObj, ok ? "COMMIT" : "ROLLBACK", 0, 0, 0);
}
else
{
    NSLog(@"Error preparing statement: %s", sqlite3_errmsg(databaseRefObj));
}


text:
Q: Unity in Native iOS App Crashes after Build Struggled a lot to build Unity in Native app. Tried to sort out all the prebuild errors but after build when app run it crashes. Screen shot

My AppDelegate code is:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame: [UIScreen mainScreen]. bounds];
    self.window.backgroundColor = [UIColor blueColor];
   // [self.window makeKeyAndVisible];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ViewController *mainVC = [storyboard instantiateViewControllerWithIdentifier:@"MainIdentity"];
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:mainVC];
    self.window.rootViewController = naVC;
    self.unityController = [[UnityAppController alloc] init];
    [self.unityController application:application didFinishLaunchingWithOptions: launchOptions];

    return YES;

}

A: Try this steps
1 - Open CrashReporter.mm in classes file
2 - search this func name InitCrashHandling
3- comment this line
#if ENABLE_CUSTOM_CRASH_REPORTER
// InitCrashReporter();
#endif

redpajama_set_name: RedPajamaStackExchange


text: Q: What are alternatives now for showinfo since it's been deprecated? I have a Youtube video embedded on our Learning Management System that needs to have sharing disabled. Now that showinfo no longer works, what other options do I have?


text:
Q: Need help modifying this regex: ^\d+\.[ \t]+(.+)[ \t]+by[ \t]+(.+)$ I'm using this regex:
^\d+\.[ \t]+(.+)[ \t]+by[ \t]+(.+)$

on this string:
1. Gulliver's Travels by Jonathan Swift

and performing this replacement:
\2 \1

to get this result:
Jonathan Swift Gulliver's Travels

However, I found another use case in my data where the author is not separated with by but by a colon and the order is reversed. Instead, it's
<number><period><space><author>:<space><title>

like this:
1. Jonathan Swift: Gulliver's Travels

How can I modify the original regex to get the same output as before?

A: Maybe you can use the following regex (I suppose there are no spaces before the colon, according to your example):
^\d+\.[ \t]+(.+)([ \t]+by|:)[ \t]+(.+)$
That way, if you capture a "by" in \2 you can do \3 \1, else you can do \1 \3.
Edit:
Here's a simple Perl program demonstrating the above:
$input = <STDIN>;
chomp($input);

if($input =~ m/^\d+\.[ \t]+(.+)([ \t]+by|:)[ \t]+(.+)$/) {
    if($2 eq ":") {
    print "$1 $3\n";
    }
    else {
    print "$3 $1\n";
    }
}

A: You could try something like: ^\d+\.\s(.+):\s(.+)\s*$

A: I, personally, would replace by in your regex with a non-capturing (?:by|\x3A) Also, not too familiar with replaced captured, but can you applied named groups to it (or otherwise explicitly make one capture \1 and the other \2)?


text:
Q: For loop indentation is not taking place in jinja2 templating in vscode I am writing a for loop or if else using jinja2 templating but it is not giving me indentation in vscode. Fore example, I wrote this:
{% extends 'base.html' %}
{% block content %}

This is Item List

{% for item in items %}

{{items}}

{% endfor %}

{% endblock content %}

But when I press Ctrl s or save it manually, it loses the indentation. The code becomes like this:
{% extends 'base.html' %}
{% block content %}

This is Item List

{% for item in items %}

{{items}}

{% endfor %}

{% endblock content %}

This is happening for for loops, if else and everything inside jinja2 templating. Not happening in normal python codes.
This is not giving any error, but I feel distressed. How to solve it.

A: You need to download this extension to format the .j2 file https://marketplace.visualstudio.com/items?itemName=monosans.djlint


text:
Q: Creating PendingIntent inside BroadcastReceiver's onReceive() Have a BroadcastReceiver which I want to create a PendingIntent inside the onReceive method
public class MyPushNotificationReceiver extends BroadcastReceiver {
..
    public void onReceive(Context context, Intent intent) {

        // How to start a PendingIntent here?

    }

Most of the doc from Google is not starting within the onReceive method, so any sample cod e I can use?
Thanks.

A: a sample code which uses a pending intent in broadcast reciver   pls check
    public class MyScheduleReceiver extends BroadcastReceiver {

// Restart service every 30 minute
private static final long REPEAT_TIME = 1000 * 30 ;

@Override
public void onReceive(Context context, Intent intent) {
    AlarmManager service = (AlarmManager) context
            .getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, MyStartServiceReceiver.class);
    PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
            PendingIntent.FLAG_CANCEL_CURRENT);
    Calendar cal = Calendar.getInstance();
    // Start 30 seconds after boot completed
    cal.add(Calendar.SECOND, 30);
    //
    // Fetch every 30 seconds
    // InexactRepeating allows Android to optimize the energy consumption
    service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
            cal.getTimeInMillis(), REPEAT_TIME, pending);

    // service.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
    // REPEAT_TIME, pending);

}
     }

this code is from vogella ...


text:
Q: Ajax load page content in div but keep the "open in new tab" on right click I'm working on a new website with a mysql database that sort a bunch of items in different categories and subcategories. I created a cool script that load dynamically the content of the category (page content) in a div without reloading the page. When you load the content, it also changes the url in the address bar and if you reload the page from this url, you will see the content of the right category. The thing is that I want to keep the "open in new tab" on right clik that every browser provides and I don't find a way to have it because the content is loaded from a javascript/ajax function.
I thought that

would work instead of

but the "open in new tab" doesn't show up in firefox and give a "about:blank" page in chrome. In Firefox, if I keep CTRL pressed and then click, it works but the url is "javascript:%20liveresults('mycategory');" and I don't know what to do next.
Is there someone having an idea about how should I proceed? Maybe I should try to create my own custom right click menu like http://grooveshark.com/

A: Try this:
function loadContent(event, param) {
    if (!event.ctrlKey) {
        console.log(param)
        return false
    } else
        return true
}

Testo

I think, no need to explain.
Also, style aspect, I would suggest you to do it this way:
function loadContent(event) {
    if (!event.ctrlKey) {
        console.log(event.target.dataset.category)
        return false
    } else
        return true
}

Testo

It may not work in old IEs (which has srcElement instead of target), but in my opinion looks cooler. But doesn't matter really.
Or, actually (maybe it's too much =) you could get rid of double specifying the address:
function loadContent(event) {
    if (!event.ctrlKey) {
        var part_of_url = event.target.href.split('/')[3]
        // maybe some other extraction method, now 'mail'
        console.log(part_of_url)
        return false
    } else
        return true
}

Testo


text:
Q: Java + Android Jetpack + Dagger 2 Inject in ViewModel I just learned dagger 2, then i want implement with android jetpack. but i have problem cannot inject variabel in ViewModel.
This my structure

*

*dagger
-- AppComponent.java
-- AppInjector.java
-- AppModule.java
-- Injectable.java

*factory
-- MainViewModelFactory.java

*module
-- FragmentBuildersModule.java
-- MainActivityModule.java
-- ViewModelKey.java
-- ViewModelModule.java
-- ViewModelSubcomponent.java

*ui
-- MainFragment.java
-- MainViewModel.java
App.java
MainActivity.java
My Code MainViewModelFactory.java
@Singleton
public class MainViewModelFactory implements ViewModelProvider.Factory {
private final Map<Class<? extends ViewModel>, Provider<ViewModel>> creators;

@Inject
public MainViewModelFactory(Map<Class<? extends ViewModel>, Provider<ViewModel>> creators) {
    this.creators = creators;
}

@SuppressWarnings("unchecked")
@Override
public <T extends ViewModel> T create(Class<T> modelClass) {
    Provider<? extends ViewModel> creator = creators.get(modelClass);
    if (creator == null) {
        for (Map.Entry<Class<? extends ViewModel>, Provider<ViewModel>> entry : creators.entrySet()) {
            if (modelClass.isAssignableFrom(entry.getKey())) {
                creator = entry.getValue();
                break;
            }
        }
    }
    if (creator == null) {
        throw new IllegalArgumentException("unknown viewmodel class " + modelClass);
    }
    try {
        return (T) creator.get();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
}

FragmentBuildersModule.java
@Module
public abstract class FragmentBuildersModule {

    @ContributesAndroidInjector
    abstract MainFragment contributeMainFragment();
}

MainActivityModule.java
@Module
public abstract class MainActivityModule {

    @ContributesAndroidInjector(modules = FragmentBuildersModule.class)
    abstract MainActivity cotributeMainActivity();
}

ViewModelKey.java
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@MapKey
@interface ViewModelKey {
    Class<? extends ViewModel> value();
}

ViewModelModule.java
@Module
public abstract class ViewModelModule {

    @Binds
    @IntoMap
    @ViewModelKey(MainViewModel.class)
    abstract MainViewModel bindMainViewModel(MainViewModel mainViewModel);

    @Binds
    abstract ViewModelProvider.Factory bindViewModelFactory(MainViewModelFactory factory);

}

ViewModelSubComponent.java
@Subcomponent
public interface ViewModelSubcomponent {

    @Subcomponent.Builder
    interface Builder {
        ViewModelSubcomponent build();
    }

    MainViewModel mainViewModel();
}

ui.MainFragment.java
public class MainFragment extends Fragment {

    private static final String TAG = "MainFragment";

    @Inject
    ViewModelProvider.Factory viewModelFactory;

    private MainViewModel mViewModel;

    public static MainFragment newInstance() {
        return new MainFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        return inflater.inflate(R.layout.main_fragment, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
//        mViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
        mViewModel = ViewModelProviders.of(this, viewModelFactory).get(MainViewModel.class);
        // TODO: Use the ViewModel

        TextView message = (TextView) getView().findViewById(R.id.message);

        message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

//                String test = mViewModel.getGlobalCommon().getNama();
                GlobalCommon globalCommon = mViewModel.getGlobalCommon();
                Toast.makeText(getContext(), "tst", Toast.LENGTH_LONG).show();
            }
        });
    }

}

di.AppComponent.java
@Singleton
@Component(modules = { AndroidInjectionModule.class, AppModule.class, MainActivityModule.class})
public interface AppComponent {

    @Component.Builder
    interface Builder {
        @BindsInstance
        Builder application(Application application);
        AppComponent build();
    }

    void inject(App app);
}

di.AppInjector.java
public class AppInjector {

    private AppInjector() {}

    public static void init(App app) {
        DaggerAppComponent.builder().application(app).build().inject(app);
        app.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle bundle) {
                handleActivity(activity);
            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });
    }

    private static void handleActivity(Activity activity) {
        if(activity instanceof HasSupportFragmentInjector){
            AndroidInjection.inject(activity);
        }

        if(activity instanceof FragmentActivity){
            FragmentManager.FragmentLifecycleCallbacks fragmentCallback = new FragmentManager.FragmentLifecycleCallbacks() {
                @Override
                public void onFragmentCreated(FragmentManager fm, Fragment f,
                                              Bundle savedInstanceState) {
                    if (f instanceof Injectable) {
                        AndroidSupportInjection.inject(f);
                    }
                }
            };

            ((FragmentActivity) activity).getSupportFragmentManager()
                    .registerFragmentLifecycleCallbacks(fragmentCallback, true);
        }
    }

}

di.AppModule.java
@Module(includes = ViewModelModule.class )
public class AppModule {

    @Provides
    @Singleton
    Context provideApplication(Context application) {
        return application.getApplicationContext();
    }

    @Singleton
    @Provides
    GlobalCommon provideGlobalCommon(){
        return new GlobalCommon();
    }

}

App.java
public class App extends Application implements HasActivityInjector {

    @Inject
    DispatchingAndroidInjector<Activity> dispatchingAndroidInjector;

    @Override
    public void onCreate() {
        super.onCreate();
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        }
        AppInjector.init(this);
    }

    @Override
    public DispatchingAndroidInjector<Activity> activityInjector() {
        return dispatchingAndroidInjector;
    }
}

MainActivity.java
public class MainActivity extends AppCompatActivity implements  HasSupportFragmentInjector {

    @Inject
    DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container, MainFragment.newInstance())
                    .commitNow();
        }
    }

    @Override
    public AndroidInjector<Fragment> supportFragmentInjector() {
        return dispatchingAndroidInjector;
    }

}

myerror:
error: [Dagger/MissingBinding] [dagger.android.AndroidInjector.inject(T)] java.util.Map<java.lang.Class<? extends android.arch.lifecycle.ViewModel>,javax.inject.Provider<android.arch.lifecycle.ViewModel>> cannot be provided without an @Provides-annotated method.
java.util.Map<java.lang.Class<? extends android.arch.lifecycle.ViewModel>,javax.inject.Provider<android.arch.lifecycle.ViewModel>> is injected at
main.main.xxx.main.main.testdagger2.factory.MainViewModelFactory.<init>(creators)
main.main.xxx.main.main.testdagger2.factory.MainViewModelFactory is injected at
main.main.xxx.main.main.testdagger2.module.ViewModelModule.bindViewModelFactory(factory)
android.arch.lifecycle.ViewModelProvider.Factory is injected at
main.main.xxx.main.main.testdagger2.ui.main.MainFragment.viewModelFactory
main.main.xxx.main.main.testdagger2.ui.main.MainFragment is injected at
dagger.android.AndroidInjector.inject(T)
component path: main.main.xxx.main.main.testdagger2.di.AppComponent → main.main.xxx.main.main.testdagger2.module.MainActivityModule_CotributeMainActivity.MainActivitySubcomponent → main.main.xxx.main.main.testdagger2.module.FragmentBuildersModule_ContributeMainFragment.MainFragmentSubcomponent

please helpme.

A: i have created a Demo application to Demonstrate the Use of LiveData, RxJava2, Dagger2, Paging, and much more. Since it is too much of the code to post here, I will post the link here. If you think you can make it easier or better open an issue.
https://github.com/mtangoo/Kasuku-Muvi

A: I wrote a library that should make this more straightforward: https://github.com/radutopor/ViewModelFactory
@ViewModelFactory
class SampleViewModel(@Provided private val repository: Repository, private val userId: Int) : ViewModel() {
    private val greeting = MutableLiveData<String>()

    init {
        val user = repository.getUser(userId)
        greeting.value = "Hello, $user.name"
    }

    fun getGreeting() = greeting as LiveData<String>
}

In the view:
class SampleActivity : AppCompatActivity() {
    @Inject
    lateinit var sampleViewModelFactory2: SampleViewModelFactory2

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sample)
        appComponent.inject(this)

        val userId = intent.getIntExtra("USER_ID", -1)
        val viewModel = ViewModelProviders.of(this, sampleViewModelFactory2.create(userId))
            .get(SampleViewModel::class.java)

        viewModel.getGreeting().observe(this, Observer { greeting ->
            greetingTextView.text = greeting
        })
    }
}


text:
Q: Remove highlighting from selection I have a script that runs if I initiate it from the VBA editor, but not when I initiate it directly from Word.
The script defines acronyms in Word documents. Before the Word file comes to me, it goes through a first-level edit in which the editor highlights terms. Because my script also uses highlighting, I have it replace the existing highlighting with colored text.
'Turn track changes off, replace yellow highlighting from FLEs with colored text to avoid confusion between
'FLE highlighting and acronym defininer highlighting
ActiveDocument.TrackRevisions = False
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting

With Selection.Find

    .Highlight = True

    With .Replacement

        .Highlight = False
        .Font.Color = RGB(155, 187, 89)

    End With

    .Execute Replace:=wdReplaceAll, Wrap:=wdFindStop

End With

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting

When I run the script from Word, it skips that entire block of code. Everything else works as it should, but the highlighting from the first-level edit remains.
When I run from the VBA editor, everything works as intended.
When I make other changes (e.g., I just updated one of the forms that the macro calls to add an explanation for the green text), they come through, no matter where I starting the script from.
Below is the entire script.
Option Explicit
Public Definitions(5) As String

Sub Acronym_Definer()
    'Defines Workbook and Worksheet, Opens Excel
    Dim xlApp As Excel.Application
    Dim xlWbk As Workbook
    Dim FN As String: FN = "C:\Users\" & Environ$("Username") & "\AppData\Roaming\Gartner\AcronymDefiner\AcronymDefiner.xlsx"

    Dim Current_Row As Long: Current_Row = 2

    Set xlApp = New Excel.Application
    xlApp.Visible = False
    Set xlWbk = xlApp.Workbooks.Open(FN)

    'Determines whether Track Changes is on or off so it can be returned to original state at end of macro
    Dim Track_Changes As Boolean
    If ActiveDocument.TrackRevisions = False Then

        Track_Changes = False

    End If

    'Changes to Simple View in Track Changes to keep deleted text from coming up in searches throughout the macro
    With ActiveWindow.View.RevisionsFilter
        .Markup = wdRevisionsMarkupSimple
        .View = wdRevisionsViewFinal
    End With

    'Turn track changes off, replace yellow highlighting from FLEs with colored text to avoid confusion between
    'FLE highlighting and acronym defininer highlighting
    ActiveDocument.TrackRevisions = False
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting

    With Selection.Find

        .Highlight = True

        With .Replacement

            .Highlight = False
            .Font.Color = RGB(155, 187, 89)

        End With

        .Execute Replace:=wdReplaceAll, Wrap:=wdFindStop

    End With

    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting

    'Begins acronym definition loop
    Do While Current_Row <= xlWbk.ActiveSheet.UsedRange.Rows.Count

        'Use to decide which column to check for NNTD status
        Dim NNTD_Column As Integer
        Dim NNTD As Boolean: NNTD = False

        Dim Chosen_Definition As String
        Dim Current_Acronym As String: Current_Acronym = xlWbk.ActiveSheet.Cells(Current_Row, 1)
        Dim User_Skip As Boolean

        Selection.HomeKey unit:=wdStory

        With Selection.Find

            .ClearFormatting
            '.Font.Color = wdColorAutomatic
            .Text = Current_Acronym
            .MatchCase = True
            .MatchWholeWord = True
            .Wrap = wdFindStop

        End With

        'Check for presence of acronym
        If Selection.Find.Execute Then

            'How many definitions does this acronym have?
            Dim Number_Definitions As Integer: Number_Definitions = xlWbk.ActiveSheet.Cells(Current_Row, 2)

            'There's only one definition; the definition is in column 3 and the NNTD status is in column 4
            If Number_Definitions = 1 Then

                Chosen_Definition = xlWbk.ActiveSheet.Cells(Current_Row, 3)
                NNTD_Column = 4
                NNTD = xlWbk.ActiveSheet.Cells(Current_Row, NNTD_Column)
                User_Skip = False

            'There's more than one definition; put definitions into array and get definition from user form
            Else

                'Ensures Array is empty at start of each loop
                Erase Definitions

                'Adds the definitions to Definitions array
                Dim i As Integer
                Dim Current_Column As Integer: Current_Column = 3

                For i = 1 To Number_Definitions

                    Definitions(i - 1) = xlWbk.ActiveSheet.Cells(Current_Row, Current_Column)
                    Current_Column = Current_Column + 2

                Next i

                'Opens userform to allow user to choose from the available definitions
                Load DefinitionList
                DefinitionList.lstAvailableDefinitions.List = Definitions
                DefinitionList.Show

                'Did the user select an option?
                If IsNull(DefinitionList.lstAvailableDefinitions.Value) Then

                    User_Skip = True

                Else

                    'Assigns user selection to Chosen_Definition variable
                    Chosen_Definition = DefinitionList.lstAvailableDefinitions.Value

                    User_Skip = False

                    'Determines NNTD column
                    Dim j As Integer
                    For j = LBound(Definitions) To UBound(Definitions)

                        If Definitions(j) = Chosen_Definition Then
                        NNTD_Column = (2 * j) + 4
                        Exit For
                        End If

                    Next j

                    Unload DefinitionList

                NNTD = xlWbk.ActiveSheet.Cells(Current_Row, NNTD_Column)

                End If

            End If

            'Acronym is NNTD
            If NNTD = True Then

                'Highlights NNTD acronyms in yellow.
                Options.DefaultHighlightColorIndex = wdYellow
                Selection.HomeKey unit:=wdStory

                With Selection.Find

                    '.Font.Color = wdColorAutomatic
                    .Text = Current_Acronym
                    .MatchCase = True
                    .MatchWholeWord = True

                    With .Replacement

                        .Highlight = True
                        .Text = ""

                    End With

                    .Execute Replace:=wdReplaceAll, Wrap:=wdFindStop

                End With

            'User chose to skip or clicked OK without selecting an option; highlight all instances of acronym in red
            ElseIf User_Skip = True Then

                Unload DefinitionList

                Options.DefaultHighlightColorIndex = wdRed
                Selection.HomeKey unit:=wdStory

                With Selection.Find

                    '.Font.Color = wdColorAutomatic
                    .Text = Current_Acronym
                    .MatchCase = True
                    .MatchWholeWord = True

                    With .Replacement

                        .Highlight = True
                        .Text = ""

                    End With

                    .Execute Replace:=wdReplaceAll, Wrap:=wdFindStop

                End With

            'Acronym needs to be defined
            Else

                'Selects first instance of acronym. Get start position of first instance of acronym.
                Selection.HomeKey unit:=wdStory
                Selection.Find.Execute Current_Acronym
                Dim AcronymStart As Long: AcronymStart = Selection.Start

                'Determines whether definition occurs in document
                Selection.HomeKey unit:=wdStory
                With Selection.Find

                    '.Font.Color = wdColorAutomatic
                    .Text = Chosen_Definition
                    .MatchCase = False
                    .Execute Wrap:=wdFindStop

                End With

                'Definition doesn't occur; insert definition before first definition of acronym and add
                'parentheses around acronym
                If Selection.Find.Found = False Then

                    Selection.HomeKey unit:=wdStory

                    With Selection.Find

                        '.Font.Color = wdColorAutomatic
                        .Text = Current_Acronym
                        .MatchCase = True
                        .Execute

                    End With

                    With Selection

                        .InsertBefore Chosen_Definition & " ("
                        .InsertAfter ")"

                    End With

                'Definition occurs in document; get end position of definition and compare to start position of acronym
                '(should be two lower than acronym)
                Else

                    Selection.HomeKey unit:=wdStory
                    Selection.Find.Execute Chosen_Definition
                    Dim DefinitionEnd As Long: DefinitionEnd = Selection.End

                    'Acronym is correctly defined; no further action is needed to define the acronym
                    If DefinitionEnd = AcronymStart - 2 Then

                    'Definition occurs after acronym; insert definition before first instance of acronym
                    ElseIf DefinitionEnd > AcronymStart Then

                        'Moves to first instance of acronym
                        Selection.HomeKey unit:=wdStory

                        'Adds definition and places parentheses around acronym
                        With Selection.Find

                            '.Font.Color = wdColorAutomatic
                            .Text = Current_Acronym
                            .MatchCase = True
                            .Execute

                        End With

                        With Selection

                            .InsertBefore Chosen_Definition & " ("
                            .InsertAfter ")"

                        End With

                    'Definition occurs before (but not immediately prior to) acronym
                    Else

                        Selection.HomeKey unit:=wdStory
                        Selection.Find.Execute Chosen_Definition

                        'Inserts acronym (surrounded by parentheses) after definition
                        With Selection

                            .InsertAfter " (" & Current_Acronym & ")"

                        End With

                    End If

                End If

                'Replace subsequent instances of acronym *and* definition with just acronym
                Dim Defined_Acronym As String: Defined_Acronym = Chosen_Definition & " (" & Current_Acronym & ")"

                'Moves cursor to follow first instance of Defined_Acronym
                Selection.HomeKey unit:=wdStory

                With Selection.Find

                    '.Font.Color = wdColorAutomatic
                    .Text = Defined_Acronym
                    .MatchCase = False
                    .Execute

                End With

                'Performs actual replacement of all but first instance of Defined_Acronym with acronym.
                Selection.HomeKey unit:=wdStory

                With Selection.Find

                    '.Font.Color = wdColorAutomatic
                    .Text = Defined_Acronym
                    .MatchCase = False
                    .Execute

                End With

                Selection.EndOf unit:=wdWord, Extend:=wdMove

                With Selection.Find

                    '.Font.Color = wdColorAutomatic
                    .Text = Defined_Acronym
                    .MatchCase = False

                    With .Replacement

                        .Highlight = False
                        .Text = Current_Acronym

                    End With

                    .Execute Wrap:=wdFindStop, Replace:=wdReplaceAll

                End With

                'Replace subsequent instances of definition (by itself) with acronym
                'Moves cursor to follow first instance of Defined_Acronym
                Selection.HomeKey unit:=wdStory

                With Selection.Find

                    '.Font.Color = wdColorAutomatic
                    .Text = Defined_Acronym
                    .MatchCase = False
                    .Execute

                End With

                Selection.EndOf unit:=wdWord, Extend:=wdMove

                With Selection.Find

                    '.Font.Color = wdColorAutomatic
                    .Text = Chosen_Definition
                    .MatchCase = False

                    With .Replacement

                        .ClearFormatting
                        .Text = Current_Acronym

                    End With

                    .Execute Replace:=wdReplaceAll, Wrap:=wdFindStop

                End With

                'Set highlight color to teal for non-NNTD acronyms, highlight all instances of Current_Acronym
                Options.DefaultHighlightColorIndex = wdTeal
                Selection.HomeKey unit:=wdStory

                With Selection.Find

                    .ClearFormatting
                    '.Font.Color = wdColorAutomatic
                    .Text = Current_Acronym
                    .MatchCase = True
                    .MatchWholeWord = True

                    With .Replacement

                        .Highlight = True
                        .Text = ""

                    End With

                    .Execute Replace:=wdReplaceAll, Wrap:=wdFindStop

                End With

            End If

        End If

        'Ends acronym definition loop
        Current_Row = Current_Row + 1

    Loop

    'Returns track changes to same status it was in when script began
    If Track_Changes = False Then

        ActiveDocument.TrackRevisions = False

    End If

    'Returns view to show all track changes
    With ActiveWindow.View.RevisionsFilter
        .Markup = wdRevisionsMarkupAll
        .View = wdRevisionsViewFinal
    End With

    Load Instructions
    Instructions.Show

    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting

    'Closes Excel
    xlWbk.Close SaveChanges:=False
    xlApp.Quit

End Sub

Function Define_Acronym()

End Function

A: Depending upon how you call the macro a Selection may not exist at first. Bear in mind that Selection.Find essentially means "Find [whatever] in the range specified by the current selection". Seeing that you collapse the selection to nothing with Selection.Homekey Unit:=WdStory I tried to figure out why your code works at all and failed. For some reason best known to itself Word seems to agree to search the entire document when the selection is 0 (or 1). But zero isn't the same as Nothing.
The better way is to specify the Range or Selection you wish to search. Either way it should be ActiveDocument.Content if you wish to search the entire body of the document. While your code is based on using the Selection object you must make such a selection, for example, ActiveDocument.Content.Select.
@Slai and I would recommend not to use the Selection object at all. Use a Range object instead. Read about the difference at MSDN


text:
Q: function "fwrite" write incorrect content I have file (filename: inc.php) with code in site:
<?php
$menu['Position1']['menu1'][]='module1';
$menu['Position1']['menu2'][]='module2';
?>

I want change code of this file to add new node array to it. then I test simple code:
include 'inc.php';

//add new value to array
$menu['Position3']['menu3'][]='module3';
$menu['Position4']['menu4'][]='module4';

//create string with fomat above
$text ='<?php ' ."\n";
foreach($menu as $position_tmp => $value1_tmp){
foreach($value1_tmp as $menu_tmp => $value2_tmp){
foreach($value2_tmp as $component_tmp){
$text .= "\$menu['" .$position_tmp ."']['" .$menu_tmp ."'][]='" .$component_tmp ."'; \n";
}
}
}
$text .= '?>';

Then I test $text. var_dump($text); output:
<?php
$menu['Position1']['menu1'][]='module1';
$menu['Position1']['menu2'][]='module2';
$menu['Position3']['menu3'][]='module3';
$menu['Position4']['menu4'][]='module4';
?>

It's OK. I write to file inc.php:
$fp = fopen('inc.php', 'w+');
fwrite($fp,$text);
fclose($fp);

Content of inc.php:
<?php
$menu['Position1']['menu1'][]='module1';
$menu['Position1']['menu2'][]='module2';
$menu['Position3']['menu3'][]='module3';
$menu['Position3']['menu3'][]='module3';
$menu['Position3']['menu3'][]='module3';
$menu['Position4']['menu4'][]='module4';
$menu['Position4']['menu4'][]='module4';
$menu['Position4']['menu4'][]='module4';
?>

I don't know why!
Then I test write new file: newfile.php. Then content of newfile.php is correct.
<?php
$menu['Position1']['menu1'][]='module1';
$menu['Position1']['menu2'][]='module2';
$menu['Position3']['menu3'][]='module3';
$menu['Position4']['menu4'][]='module4';
?>

I try delete inc.php, rename newfile.php to inc.php
sleep(5); // I open newfile.php. It's correct.
unlink('inc.php');
rename('newfile.php','inc.php');

inc.php still incorrect. I can't understand. Please to help me!

A: Appending '<?php' string with your $text will cause a problem. Better to use:
$php_open_tag    = htmlentities('<?php'); // Or try like this htmlspecialchars('<?php');
$php_close_tag   = htmlentities('?>');
$text = $php_open_tag . 'YOUR CONTENT' . $php_close_tag ;
$text = str_replace('<','<',$text);
$text = str_replace('>','>',$text);

and then try to write your content.
$fp = fopen('inc.php', 'w+');
fwrite($fp,$text);
fclose($fp);

I hope this works for you.


text:
Q: Sum time output from processes (bash) I've made an script which measure the time of some processes. This is the  file  that I get:
real    0m6.768s
real    0m5.719s
real    0m5.173s
real    0m4.245s
real    0m5.257s
real    0m5.479s
real    0m6.446s
real    0m5.418s
real    0m5.654s

The command I use to get the time is this one:
{ time my-command } |& grep real >> times.txt

What I need is to sum all this times and get as a result how many (hours if applies) minutes and seconds using a bash script.

A: From man bash, then if PAGER is less / time.

  If the time reserved word precedes a pipeline, the elapsed as well as user and system time consumed by its  exe-
  cution  are reported when the pipeline terminates.  The -p option changes the output format to that specified by
  POSIX.  The TIMEFORMAT variable may be set to a format string that specifies how the timing  information  should
   be displayed; see the description of TIMEFORMAT under Shell Variables below.

then /TIMEFORMAT

         The  optional  l  specifies  a  longer  format, including minutes, of the form MMmSS.FFs.  The value of p
         determines whether or not the fraction is included.

         If this variable is not set, bash acts as if it had the value  $'\nreal\t%3lR\nuser\t%3lU\nsys%3lS'.   If
         the  value  is  null,  no  timing  information is displayed.  A trailing newline is added when the format
         string is displayed.

If it can be changed to something like
TIMEFORMAT=$'\nreal\t%3R'

without the l, it may be easier to sum.
Note also format may depend on locale LANG:
compare
(LANG=fr_FR.UTF-8; time sleep 1)

and
(LANG=C; time sleep 1)

In that case the sum can be done with an external tool like awk
awk '/^real/ {sum+=$2} END{print sum} ' times.txt

or perl
perl -aln -e '$sum+=$F[1] if /^real/; END{print $sum}' times.txt

A: Pipe the output to this command
grep real | awk '{ gsub("m","*60+",$2); gsub("s","+",$2); printf("%s",$2); } END { printf("0\n"); }' | bc

This should work if you have generated the output using built-in time command. The output is in seconds.


text:
Q: Access 2013 Frontend fails to load - backend linking Issue I splitted the database, and then did some changes directly into backend. and then i tried to open front end, it failed to open and just asking for new/other files to open. what am i missing here ?
I gave up and opened my another backup access file and splitted it in frontend-backend. let say frontend name :DBstore7_fe and backend name:Dbstore7_be. link is ok and i can update data from front end. but i have to keep my old version of backend(Dbstore6_be) in the same folder. if i remove this old backend version, my frontend fails to open.
i tried another thing, i imported back all the tables to the front end, i.e - no more backend/linking. but still it is looking for Dbstore6_be. if this one there ....my database loads otherwise prompting for blank version.

A: You must run the "External Data", "Manage Linked Tables" wizard whenever you move or modify the backend file.


text: Q: Portable method in C++ to determine special folder locations (Downloads, Documents, Preferences, etc.) I've been searching for a portable method in Boost or C++17 std::filesystem (or POSIX) to determine the system sanctioned locations of the user's Documents, Downloads, and Preferences.  Do these locations really need to be hard-wired, or is there a C/C++ accessible API for those locations? (portable between Windows/MacOS and ideally iOS/Android)


text:
Q: Проверить существование класса по имени в строковой переменной cl = "className";
Как проверить существование класса по имени в строковой переменной cl?
А затем, если он существует, создать объект этого класса.

A: Как таковых классов в EMAScript нет. Есть функции-конструкторы.
Проверить, является ли строка названием конструктора можно так

function constr() {return {a: true}};

let name = "constr";

let exists = typeof window[name] === "function";
console.log(exists)

if (exists) {
    var c = new window[name]();
}

console.log(c);

В этом случае мы проверяем, является ли свойство name, содержащее название класса, функцией. Если является, значит такая функция есть, а любая функция может быть вызвана как конструктор.
Можно и при помощи eval (но помним об eval is evil). Полезно для синтаксиса ES6, где есть ключевое слово class, которое не попадает в window в виде функции, хотя ей же и является.

class K {
    constructor() {
        return {a: 1};
    }
}

let name = "K";

let exists = eval("typeof " + name + " === 'function';");
console.log(exists);

A: Если я правильно понял ваш вопрос, то вот так:
function Rabbit() {}

// создаём объект
var rabbit = new Rabbit();

// проверяем -- этот объект создан Rabbit?
if( rabbit instanceof Rabbit ){ // если возвращает true - создаем новый объект этого класса
     var rabbit_2 = new Rabbit();
}


text:
Q: How to get a related object sorted with Entity Framework for ASP.NET MVC Having two classes like Blog and Post, in Entity Framework (and LINQ-to-Entities), how can you get the blogs with the posts sorted by date. I was getting the blogs with the posts this way:
from blog in db.BlogSet.Include("Posts") select blog

and now I'm forced to do this:
public class BlogAndPosts {
    public Blog Blog { get; set; }
    public IEnumerable<Post> Posts { get; set; }
}

from blog in db.BlogSet
select new BlogAndPosts () {
    Blog = blog,
    Posts = blog.Posts.OrderByDescending(p => p.PublicationTime)
}

which is very convoluted and ugly. The reason why I'm creating a BlogPosts class is that now, since I have to pass two variables, Blog and Posts, to MVC, I need a view model.
I'm even tempted to try this hack:
from blog in db.BlogSet
select new Blog(blog) {
    Posts = blog.Posts.OrderByDescending(p => p.PublicationTime)
}

but what's the correct way to do it? Is Entity Framework not the way to go with MVC?

A: I generally create a presentation model type wholly unaware of the Entity Framework and project into that. So I would do something like:
public class PostPresentation {
    public Guid Id { get; set; }
    public string Title { get; set; }
    public DateTime PostTime { get; set; }
    public string Body { get; set; }
}

public class BlogHomePresentation {
    public string BlogName { get; set; }
    public IEnumerable<Post> RecentPosts { get; set; }
}

from blog in db.BlogSet
select new BlogHomePresentation
{
    BlogName = blog.name,
    RecentPosts = (from p in blog.Posts
                   order by p.PublicationTime desc
                   select new PostPresentation
                   {
                       Id = p.Id,
                       Title = p.Title,
                       PostTime = p.PublicationTime,
                       Body = p.Body
                   }).Take(10)
}

Does this seem like a lot of work? Consider the advantages:

*

*Your presentation is entirely ignorant of your persistence. Not "ignorant as in having to make all of the properties public virtual," but entirely ignorant.

*It is now possible to design the presentation before designing the database schema. You can get your client's approval without doing so much work up front.

*The presentation model can be designed to suit the needs of the page. You don't need to worry about eager loading or lazy loading; you just write the model to fit the page. If you need to change either the page or the entity model, you can do either one without affecting the other.

*Model binding is easier with simple types. You will not need a custom model binder with this design.

A: I would also suggest to use view models. When your application grows, there may be more content on a specific view, like:
public class PostDetailResult {
    public Post<Post> Post { get; set; }
    public IList<Post> RecentPosts { get; set; }
    public IList<Post> RelatedPosts { get; set; }
    public IList<Post> MostRated { get; set; }
}

You may add another layer between controller and data abstraction like a repository, because your BL should decide what "MostRated" posts are. If you are using "MostRated" posts on multiple views you don't want to write the same query in multiple controllers. With a repository, controller code might look like this:
var result = new PostDetailResult {
    Post = repo.GetPost(id),
    RecentPosts = repo.GetRecentPosts(),
    RelatedPosts = repo.GetRelatedPosts(id)
};

Hope, this helps.


text:
Q: How do you use JsHint ".jshintrc" file with Visual Studio 2013 Web Essentials extension? I have installed the "Web Essentials" extension into Visual Studio 2013.  I am now getting JSHint warnings appearing in my "Error List" window under the Messages section.  However, it is complaining about some global variables that it thinks are not defined.
From what I read, you can use JSHint's .jshintrc file to list global variables so it will stop complaining about them.  I want to have it set up as follows.  (so that it will stop complaining about "ko"... which is a KnockoutJs global variable.)
"globals": {
    "$": false,
    "jQuery": false,
    "ko": false
 }

How and where are you supposed to create this .jshintrc file in your VS Project?
I tried adding the file in the root of the project, naming it literally as ".jshintrc" but Visual Studio complains saying that:
"File and folder names cannot contain a leading period."

I can't seem to find any documentation about how to add this file into your Visual Studio project so that the Web Essentials extension will pick it up.
Any ideas?

Update
Hex had the correct answer.  I had to open a command prompt to rename the file, as Windows Explorer wouldn't let me name a file starting with a period either.  After that, I also followed Hex's advice on surrounding the entire thing in curly braces.  Here are the contents of my .jshintrc file.... which I have sitting in my WebApp's root folder... alongside other files like web.config.
{
    "globals": {
        "$": false,
        "jQuery": false,
        "ko": false
      }
}

I no longer get 10 million unnecessary warnings about the "ko" object.  :)  Thanks Hex!

A: The easiest way to create/edit JSHint global settings (as well as TSLint, CoffeLint & JSCS settings), is to click on the Web Essentials menu, then select the appropriate option.

This way, Web Essentials takes care of creating the file for you, if it doesn't already exist.

A: Project root is fine. I thing JsHint is searching for file all the way to the top of filesystem.
You can create file using command line.
just create file using your favorite tool and then rename it from cmd like "ren jshintrc .jshintrc"
Also I found out that I need to restart VS for it to load changes in jshintrc file.
If it's still not working try to put whole file in {}. I'm not sure if it is required but I see it elsewhere.

A: I added jshint via Visual Studio extensions. Under the Menu option there is a menu item called JavaScript Linter Options... It brings up a dialog that allows you to select many different options. To remove the '$' is not defined error, I checked the Assume jQuery option.


text:
Q: Should the status field in the output of a REST-style API call be a numeric code or a string? I have a REST-ish API that returns JSON.  One of the output fields is status, which indicates if the call succeeded.  I gather that it's somewhat standard to use numeric status codes such as
200 success
400 syntax error
401 authentication error
402 general error
404 user not found
408 timed out
500 fatal error
501 not yet implemented

Are there any reasons (other than to transmit slightly fewer bytes) to use numeric codes rather than more descriptive symbols as the status, like
success
syntax_error
auth_error
general_error
user_not_found_error
time_out_error
fatal_error
not_yet_implemented_error

Pointing to modern precedents in well-respected APIs would be helpful.

A: You can make them what you want, as long as they are standard (across your app) and documented for the benefit of those using the webservice.
The fondness of using HTTP status codes such as 404 is that a true REST webservice is based on HTTP transport, so it makes sense to use recognised standards.
That said, you may find that the HTTP/1.1 status codes are not an exact fit - such as your '404 user not found' equivalent to '404 not found' - I think as long as the meaning is there then fine.
If you have to create completely new codes, it's worth sticking to the HTTP groups - 2xx for acceptable results, 3xx for required changes, 4xx for client-side errors and 5xx for server-side errors.


text:
Q: How to install PPAs (from Launchpad) on non-Ubuntu distros like Debian? AFAIK only Ubuntu and (obviously) Ubuntu-based distributions can handle  PPAs. A major (and maybe the only) source of PPAs is Launchpad - another service by Canonical.
A real-world example is Notepadqq. They only provide installation via PPA/Launchpad.
So how can I install them on non-Ubuntu distros like Debian? Can I probably download them (as a .deb file or something similar) manually from the Launchpad site?

A: You can run this command in Debian Wheezy and newer:
sudo apt-get install software-properties-common python-software-properties

Now, you can use sudo add-apt-repository ppa:some/ppa in Debian!
HOWEVER!
It will not find any packages for you! This is because it is looking for Debian packages, but PPAs hold Ubuntu packages. You need to edit the files located in:
/etc/apt/sources.list.d/YOURPPA/YOURPPA.list

And replace all DEBIAN VERSION occurrences with an Ubuntu version, I suggest Trusty as it is currently the most recent LTS version of Ubuntu.
Now, you can run:
sudo apt-get update
sudo apt-get install YOURPACKAGE

To install the package from the PPA.
Source: WebUpd8 Team

A: Here is your example - Notepadqq - installed to Debian 10.0.0 Buster.
Although Ubuntu-oriented, in fact the official notepadqq PPA repository does contain .deb files!
(I chose Ubuntu 18.04 Bionic from the technical details dropdown.)
Download both of the following .deb files:
http://ppa.launchpad.net/notepadqq-team/notepadqq/ubuntu/pool/main/n/notepadqq/notepadqq-common_1.4.4-1~bionic1_all.deb
http://ppa.launchpad.net/notepadqq-team/notepadqq/ubuntu/pool/main/n/notepadqq/notepadqq_1.4.4-1~bionic1_amd64.deb

Install via terminal as follows:
sudo dpkg -i ./notepadqq-common_1.4.4-1~bionic1_all.deb
sudo apt-get install -f

sudo dpkg -i ./notepadqq_1.4.4-1~bionic1_amd64.deb
sudo apt-get install -f

Success! ( See: /usr/share/applications/notepadqq.desktop)


text:
Q: Use ArangoDB from C++ Despite being written in C++, ArangoDB does not provide a C++ driver, limiting the choice of languages to Java, Go, C#, Node.js and Python.
Since my application is written in C++ I'm looking for ways to overcome this. Legacy docs, old SO questions and blog posts point to Fuerte which has long been discontinued.

*

*Is there an up to date C++ driver?

*If not, is using the http/REST API over something like cpp-httplib a sane choice? Are people doing this and is there a downside to it (limited features, difficulty in expressing built-in constructs like Graphs etc.)?

If the second option is suggested I'd appreciate any links to open source projects that use ArangoDB in this fashion - just to make the phrase "are people doing this" more concrete.


text:
Q: JavaScript file naming conventions when there is a space in the project name I have some JavaScript I want to make available for people to use. The JavaScript project is called, say, Sharp Knife. The key point is that it has a space in it.
How do I name the minified JS file of version 1.0 to be consistent with prevailing conventions?

*

*sharp-knife-1.0.min.js

*sharp.knife-1.0.min.js

*sharpknife-1.0.min.js

*something else?

A: Use whatever you prefer. But please don't use spaces - they are ugly in URLs (and filenames imho)
I'd probably use a CamelCased filename, i.e. SharpKnife-1.0.min.js


text:
Q: Find xpath from a webElement in python I'm trying to scrape some pages with python, working with Selenium, but I have a problem. The elements that I am looking for have different xpath, due to different page structures, but all are in the same part of the page with the same class name. So I'd like to know if there is the possibility, once I get the webElement, of knowing its class name, with the part of the page that I'm interested in, to find the XPath of this part of the page.
I'm doing this to find the part of the page:
interestedPart = driver.find_element_by_class_name("_45kb")

But after that I don't know how to find the "interestedPart" full XPath, can you help me?
Example of full XPath:
/html/body/div[1]/div/div[4...

A: yes, it's possible
element.get_attribute('class')
xpath = "//div[@class='"+element.get_attribute('class')+"']"
for your example Webelement called interestedPart:
xpath = "//div[@class='"+interestedPart.get_attribute('class')+"']"


text:
Q: Do there exist associative sudoku squares? Last night I taught an algebra tutorial, and while writing out the multiplication table for the units of $\mathbb{Z}/5\mathbb{Z}$, a student remarked that it looked like a sudoku puzzle.  I noted that it was similar, as the rows and columns all satisfy the sudoku condition, however the 2 by 2 sub-squares do not. The reason I gave is that multiplication is commutative in this group, and so the squares along the diagonal are symmetric. Afterwards I realized that there is an even simpler reason which excludes the possibility of nonabelian groups having multiplication tables which are sudoku squares: the identity element always messes up one of the sub-squares along the diagonal. This leads to the natural question: do there exist associative sudoku squares of side length $n^2$? (Meaning interpret the sudoku square as defining a binary operation on the integers $1$ through $n^2$. Is this binary operation ever associative? Of course I care about when $n > 1$ as $n = 1$ is clear.)

A: If we are not obligated to keep the same order in rows and columns of the table, the answer is yes, and the group can be chosen to be commutative. For example
the group $G=\left(\mathbb{Z}/(n\mathbb{Z})\right) ^{\times2}$,
the order of columns: $(1,1), (1,2), \dots, (1,n), (2,1), \dots, (n,n)$,
the order of rows: $(1,1), (2,1), \dots, (n,1), (1,2), \dots, (n,n)$.
Otherwise, the answer is no for any $n>1$, because in any table of this type both $a\cdot 1$ and $1\cdot a$ are in the same $n\times n$ square for some $a\in G$.
Edit: If this operation doesn't need to define a group, then the answer is no too. Here is the proof.
Suppose $G$ is $\{1,\dots,n^2\}$ endowed with some associative operation and suppose, that the table of this operation is a sudoku table. Take any $x\in G$. In $x$-th line of the table we can find element $x$. Therefore $xy=x$ for some $y\in G$. Then take $a\in G$, such that $a\neq y$ and $ay$ and $ya$ are in the same square of the table. We have $(xy)a=x(ya)$ and, therefore $xa=x(ya)$. Using, that there is only one place in $x$-th line of the table, where we can find $xa$, we see that $a=ya$. From this we have $a(ya)=(ay)a$, $aa=(ay)a$ and $a=ay$. Therefore $ay=a=ya$ and the table is not a sudoku table.


text:
Q: minimalistic way to pass json data to server using FastAPI I am trying to pass some json contents from the client to the server via some
simple REST API built with FastAPI (using uvicorn).
If I wrap the file contents into a pydantic.BaseModel like so
app = FastAPI()

class ConfigContents(BaseModel):
    str_contents: str

@app.post("/writeFile/{fn}")
async def write_file(fn: str, contents: ConfigContents):
    filepath = "/some_server_dir/" + fn
    with open(filepath, "w") as f:
        f.write(contents.str_contents)
    return contents

I essentially get what I want, i.e. on the client side (using the request-library), I can execute
response = requests.post("http://127.0.0.1:8000/writeFile/my_file.json",
             data=json.dumps({"str_contents": contents}))

and end up with the file contents assigned to response and written to the file on the "server".
My question is: is there a simpler way to achieve the same, e.g. just passing
the json contents as a string to the server without the need to wrap it into a model?

A: from the fastApi doc:

If you don't want to use Pydantic models, you can also use Body parameters. See the docs for Body - Multiple Parameters: Singular values in body.

The doc for Body explains that you can declare any parameter with a Body(...) default value to make it a value to be retrieved from the resquest body.
This means you could simply delete your pydantic model and change your write_file function declaration to:
async def write_file(fn: str, contents=Body(...)):
   ...

However, it would be a (very) bad idea in my opinion. FastApi uses the pydantic models to validate the provided data and to generate convenient API doc.
I would rather recommand to improve and develop the pydantic models you use to get better automatic validation and documentation.


text:
Q: Selenium fails to start Chromedriver in CentOS I try to start Chromedriver with Selenium
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://www.google.com/")
print(driver.title)

and error msg below:
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
 (Driver info: chromedriver=2.33.506092,platform=Linux 3.10.0-693.5.2.el7.x86_64 x86_64)

I am using these:
[root@jdu4e00u53f7 workspace]# ll /usr/local/bin/chromedriver
lrwxrwxrwx 1 root root 17 11月 14 00:31 /usr/local/bin/chromedriver -> /opt/chromedriver

*

*CentOS 7.3

*Python(3.6.2)

*selenium (3.7.0)

*Google Chrome (62.0.3202.89)

*chromedriver(2.9)/ I changed to chromedriver=2.33.506092

*Xvfb

ps, I also tried

*

*driver = webdriver.Chrome('/usr/local/bin/chromedriver'),it not work...

test.py
output
ref :Selenium fails to start Chromedriver

*On my server start Xvfb in the background:
Xvfb :0 -ac -screen 0 1024x768x24 &
and also not work

ref:unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

A: It is much evident from your mentioned configuration that you are using Selenium v3.7.0, Google Chrome 62.0 along with chromedriver v2.9 which is not compatible. Hence we are seeing the error WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally

The Release Notes of ChromeDriver v2.33 clearly mentions Supports Chrome v60-62

Solution:
Download the latest chromedriver v2.33 from this link and execute your testcase.
Update :
Try the following code block :
from selenium import webdriver
driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver')
driver.get('https://www.google.co.in')
print("Page Title is : %s" %driver.title)
driver.quit()

OR

from selenium import webdriver
driver = webdriver.Chrome(executable_path='/opt/chromedriver')
driver.get('https://www.google.co.in')
print("Page Title is : %s" %driver.title)
driver.quit()


text:
Q: SxS error in Windows 7 when trying to run a Matlab-Compiler-Runtime application I'm trying to run a data analysis tool that was built as a standalone Matlab application on a Windows 7 machine.  I've installed the Matlab Compiler Runtime (MCR) libraries version 7.11, 2009b.  When I attempt to launch the application ELISAgui.exe I get the following error:
C:\Users\amatteson\temp\ELISAgui>ELISAgui.exe
My Own Exception: Fatal error loading library C:\Program Files (x86)\MATLAB\MATL
AB Compiler Runtime\v711\bin\win32\mclmcr.dll Error: The application has failed
to start because its side-by-side configuration is incorrect. Please see the app
lication event log or use the command-line sxstrace.exe tool for more detail.

I first attempted a reboot.  Then a repair install of the MCR environment.  Then a delete and totally new install.  No change in the error.  So I decided to brave my inexperience with Windows (I'm very much a Linux or Mac guy) and break out the sxstrace tool.  I followed the procedure outlined here "Diagnosing side by side failures" and arrived with the following output from the tool (my sincere apologies for posting the full trace, but I'm not sure what's relevant):
=================
Begin Activation Context Generation.
Input Parameter:
    Flags = 0
    ProcessorArchitecture = Wow32
    CultureFallBacks = en-US;en
    ManifestPath = C:\Program Files (x86)\MATLAB\MATLAB Compiler Runtime\v711\bin\win32\hg.dll
    AssemblyDirectory = C:\Program Files (x86)\MATLAB\MATLAB Compiler Runtime\v711\bin\win32\
    Application Config File =
-----------------
INFO: Parsing Manifest File C:\Program Files (x86)\MATLAB\MATLAB Compiler Runtime\v711\bin\win32\hg.dll.
    INFO: Manifest Definition Identity is (null).
    INFO: Reference: Microsoft.VC80.CRT,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="8.0.50727.762"
    INFO: Reference: Microsoft.VC80.MFC,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="8.0.50727.762"
INFO: Resolving reference Microsoft.VC80.CRT,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="8.0.50727.762".
    INFO: Resolving reference for ProcessorArchitecture WOW64.
        INFO: Resolving reference for culture Neutral.
            INFO: Applying Binding Policy.
                INFO: No publisher policy found.
                INFO: No binding policy redirect found.
            INFO: Begin assembly probing.
                INFO: Did not find the assembly in WinSxS.
                INFO: Attempt to probe manifest at C:\Windows\assembly\GAC_32\Microsoft.VC80.CRT\8.0.50727.762__1fc8b3b9a1e18e3b\Microsoft.VC80.CRT.DLL.
                INFO: Did not find manifest for culture Neutral.
            INFO: End assembly probing.
    INFO: Resolving reference for ProcessorArchitecture x86.
        INFO: Resolving reference for culture Neutral.
            INFO: Applying Binding Policy.
                INFO: Find publisher policy at C:\Windows\WinSxS\manifests\x86_policy.8.0.microsoft.vc80.crt_1fc8b3b9a1e18e3b_8.0.50727.4927_none_516ad11f0f4bdafe.manifest
                INFO: Publisher Policy redirected assembly version.
                INFO: Post policy assembly identity is Microsoft.VC80.CRT,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="8.0.50727.4927".
            INFO: Begin assembly probing.
                INFO: Attempt to probe manifest at C:\Windows\WinSxS\manifests\x86_microsoft.vc80.crt_1fc8b3b9a1e18e3b_8.0.50727.4927_none_d08a205e442db5b5.manifest.
                INFO: Manifest found at C:\Windows\WinSxS\manifests\x86_microsoft.vc80.crt_1fc8b3b9a1e18e3b_8.0.50727.4927_none_d08a205e442db5b5.manifest.
            INFO: End assembly probing.
INFO: Resolving reference Microsoft.VC80.CRT.mui,language="*",processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="8.0.50727.4927".
    INFO: Resolving reference for ProcessorArchitecture WOW64.
        INFO: Resolving reference for culture en-US.
            INFO: Applying Binding Policy.
                INFO: No publisher policy found.
                INFO: No binding policy redirect found.
            INFO: Begin assembly probing.
                INFO: Did not find the assembly in WinSxS.
                INFO: Attempt to probe manifest at C:\Windows\assembly\GAC_32\Microsoft.VC80.CRT.mui\8.0.50727.4927_en-US_1fc8b3b9a1e18e3b\Microsoft.VC80.CRT.mui.DLL.
                INFO: Did not find manifest for culture en-US.
            INFO: End assembly probing.
        INFO: Resolving reference for culture en.
            INFO: Applying Binding Policy.
                INFO: No publisher policy found.
                INFO: No binding policy redirect found.
            INFO: Begin assembly probing.
                INFO: Did not find the assembly in WinSxS.
                INFO: Attempt to probe manifest at C:\Windows\assembly\GAC_32\Microsoft.VC80.CRT.mui\8.0.50727.4927_en_1fc8b3b9a1e18e3b\Microsoft.VC80.CRT.mui.DLL.
                INFO: Did not find manifest for culture en.
            INFO: End assembly probing.
    INFO: Resolving reference for ProcessorArchitecture x86.
        INFO: Resolving reference for culture en-US.
            INFO: Applying Binding Policy.
                INFO: No publisher policy found.
                INFO: No binding policy redirect found.
            INFO: Begin assembly probing.
                INFO: Did not find the assembly in WinSxS.
                INFO: Attempt to probe manifest at C:\Windows\assembly\GAC_32\Microsoft.VC80.CRT.mui\8.0.50727.4927_en-US_1fc8b3b9a1e18e3b\Microsoft.VC80.CRT.mui.DLL.
                INFO: Did not find manifest for culture en-US.
            INFO: End assembly probing.
        INFO: Resolving reference for culture en.
            INFO: Applying Binding Policy.
                INFO: No publisher policy found.
                INFO: No binding policy redirect found.
            INFO: Begin assembly probing.
                INFO: Did not find the assembly in WinSxS.
                INFO: Attempt to probe manifest at C:\Windows\assembly\GAC_32\Microsoft.VC80.CRT.mui\8.0.50727.4927_en_1fc8b3b9a1e18e3b\Microsoft.VC80.CRT.mui.DLL.
                INFO: Did not find manifest for culture en.
            INFO: End assembly probing.
INFO: Resolving reference Microsoft.VC80.MFC,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="8.0.50727.762".
    INFO: Resolving reference for ProcessorArchitecture WOW64.
        INFO: Resolving reference for culture Neutral.
            INFO: Applying Binding Policy.
                INFO: No publisher policy found.
                INFO: No binding policy redirect found.
            INFO: Begin assembly probing.
                INFO: Did not find the assembly in WinSxS.
                INFO: Attempt to probe manifest at C:\Windows\assembly\GAC_32\Microsoft.VC80.MFC\8.0.50727.762__1fc8b3b9a1e18e3b\Microsoft.VC80.MFC.DLL.
                INFO: Did not find manifest for culture Neutral.
            INFO: End assembly probing.
    INFO: Resolving reference for ProcessorArchitecture x86.
        INFO: Resolving reference for culture Neutral.
            INFO: Applying Binding Policy.
                INFO: No publisher policy found.
                INFO: No binding policy redirect found.
            INFO: Begin assembly probing.
                INFO: Did not find the assembly in WinSxS.
                INFO: Attempt to probe manifest at C:\Windows\assembly\GAC_32\Microsoft.VC80.MFC\8.0.50727.762__1fc8b3b9a1e18e3b\Microsoft.VC80.MFC.DLL.
                INFO: Attempt to probe manifest at C:\Program Files (x86)\MATLAB\MATLAB Compiler Runtime\v711\bin\win32\Microsoft.VC80.MFC.DLL.
                INFO: Attempt to probe manifest at C:\Program Files (x86)\MATLAB\MATLAB Compiler Runtime\v711\bin\win32\Microsoft.VC80.MFC.MANIFEST.
                INFO: Attempt to probe manifest at C:\Program Files (x86)\MATLAB\MATLAB Compiler Runtime\v711\bin\win32\Microsoft.VC80.MFC\Microsoft.VC80.MFC.DLL.
                INFO: Attempt to probe manifest at C:\Program Files (x86)\MATLAB\MATLAB Compiler Runtime\v711\bin\win32\Microsoft.VC80.MFC\Microsoft.VC80.MFC.MANIFEST.
                INFO: Did not find manifest for culture Neutral.
            INFO: End assembly probing.
    ERROR: Cannot resolve reference Microsoft.VC80.MFC,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="8.0.50727.762".
ERROR: Activation Context generation failed.
End Activation Context Generation.

Again, my sincere apologies for posting the full log, but it's Greek to me. I'm not sure how to proceed and would appreciate some pointers.

A: This looks like you're runnning a 32-bit compiled Matlab app on a 64-bit Windows machine, and it's not finding the 32-bit Visual C++ runtime it's linked against. (On 64-bit Windows, 32-bit applications run in a 32-bit subsystem and are linked against 32-bit versions of their libraries.) IIRC, the MCR installer for earlier versions may not install all of its Visual C++ Runtime dependencies. You may need to install it yourself.
I think "VC80" corresponds to Visual Studio 2005. Check your Add and Remove Programs control panel to see which "Microsoft Visual C++ XXXX Redistributable" ones are installed. (On the x64 XP box I use for Matlab development, I have nearly a dozen variants.) You'll need the 32-bit (x86) 2005 one, which is named "Microsoft Visual C++ 2005 Redistributable". It does not have " (x64)" at the end of it's name; that's the 64-bit one. They can both be installed simultaneously on a 64-bit system.
If you don't have it installed, download it from here, install it, and try running the app again. If that doesn't work, try installing the 2008 version too.
http://www.microsoft.com/download/en/details.aspx?id=5638


text:
Q: Cordova Ionic project with Firebase Messaging and Firebase Dynamic Links In the app that we're building, we need Firebase Dynamic Link, because the Sign Up is with Firebase email link login. This login will send an email to the provided email address, that when clicked, will open the app with a dynamic link. To keep our users engaged, we also like to send Push Notifications. I can get both of them to work together on Android when I use the versions by chemerisuk on GitHub. I even get an iOS build, but I get stuck on getting a token on iOS. Getting this error message:
Failed to fetch default token Error Domain=com.firebase.iid Code=1003 "(null)"

I've double checked my Firebase Project settings (bundle id, app id prefix, cloud messaging sender id, cloud messaging apn key) and my Apple settings (certificates, provisioning profiles, keys and identifiers). I've tried it on Simulators and Real Devices. I've tried Development builds, App Store Archives and Ad Hoc Archives.
Unfortunately, Dynamic Links isn't included in the Cordova Firebase plugin. When I try to add a different fcm plugin, it includes the complete Firebase Core, which conflicts with Dynamic Links.
I feel like I'm really close, who has any experience with this combination of plugins and got it working on iOS?
This is my environment:
Ionic:

  ionic (Ionic CLI)  : 4.0.2 (/usr/local/lib/node_modules/ionic)
  Ionic Framework    : ionic-angular 3.9.2
  @ionic/app-scripts : 3.1.8

Cordova:

  cordova (Cordova CLI) : 8.0.0
  Cordova Platforms     : android 7.0.0, ios 4.5.5

System:

  Android SDK Tools : 26.1.1
  ios-deploy        : 1.9.2
  ios-sim           : 6.1.2
  NodeJS            : v8.11.3 (/usr/local/bin/node)
  npm               : 5.6.0
  OS                : macOS High Sierra
  Xcode             : Xcode 9.4.1 Build version 9F2000

Environment:

  ANDROID_HOME : /Users/user/Library/Android/sdk/

My (relevant) Cordova config.xml:
<?xml version='1.0' encoding='utf-8'?>
<widget android-packageName="com.example.android" android-versionCode="10001" id="com.example.app" ios-CFBundleIdentifier="com.example.ios" ios-CFBundleVersion="1.0.1" version="1.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>Example</name>
    <description>Some description</description>
    <content src="index.html" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <preference name="ScrollEnabled" value="false" />
    <preference name="BackgroundColor" value="0xff168aa5" />
    <preference name="android-minSdkVersion" value="16" />
    <preference name="BackupWebStorage" value="none" />
    <preference name="SplashMaintainAspectRatio" value="true" />
    <preference name="FadeSplashScreenDuration" value="300" />
    <preference name="Orientation" value="portrait" />
    <preference name="SplashShowOnlyFirstTime" value="false" />
    <preference name="SplashScreen" value="screen" />
    <preference name="SplashScreenDelay" value="3000" />
    <platform name="android">
        <resource-file src="google-services.json" target="app/google-services.json" />
        <allow-intent href="market:*" />
        <icon />
        <splash />
    </platform>
    <platform name="ios">
        <resource-file src="GoogleService-Info.plist" />
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
        <icon />
        <splash />
    </platform>
    <plugin name="cordova-plugin-whitelist" spec="^1.3.3" />
    <plugin name="cordova-plugin-device" spec="^2.0.2" />
    <plugin name="cordova-plugin-splashscreen" spec="^5.0.2" />
    <plugin name="cordova-plugin-ionic-webview" spec="^1.2.1" />
    <plugin name="cordova-plugin-ionic-keyboard" spec="^2.1.2" />
    <plugin name="cordova-plugin-x-socialsharing" spec="^5.4.1" />
    <plugin name="cordova-plugin-qrscanner" spec="^2.6.0" />
    <allow-navigation href="http://192.168.178.19:8101" />
    <plugin name="cordova-plugin-firebase-dynamiclinks" spec="^1.0.0">
        <variable name="APP_DOMAIN" value="example.com" />
        <variable name="PAGE_LINK_DOMAIN" value="ab123.app.goo.gl" />
        <variable name="FIREBASE_DYNAMIC_LINKS_VERSION" value="+" />
    </plugin>
    <plugin name="cordova-plugin-firebase-messaging" spec="^1.1.0">
        <variable name="FIREBASE_MESSAGING_VERSION" value="17.1.+" />
        <variable name="ANDROID_SUPPORT_VERSION" value="27.+" />
    </plugin>
    <engine name="android" spec="7.0.0" />
    <engine name="ios" spec="4.5.5" />
</widget>

A: Because I was using only parts of the Firebase library, I didn't include Firebase Analytics, because I wasn't using it. Apparently, it's necessary for the functioning of the rest of the plugins. So installing cordova-plugin-firebase-analytics was the fix for me.
For some, it was making sure that they had the correct Firebase project settings. Go to Firebase > Cloud messaging > iOS app configuration and make sure you've uploaded a valid APNs Authentication Key or APNs Certificates.
Hope this helps other people who want to use both Firebase Messaging AND Firebase Dynamic Links!


text:
Q: modify and resize ionic popup How can I following Ionic popup (first image) modify so that it looks like the second image? Can I add more input fields and resize the popup? The purpose is to create an entry by typing some information on a server like in second image. An extra page or a new form shouldn't be opened. Especially on the same page should be created an entry by using the pop-up.
first image

second image

Code of first popup:
myApp.controller('showPopupCtrl',function($scope, $ionicPopup) {
    // Triggered on a button click, or some other target
    $scope.showPopup = function() {
        $scope.data = {}
        // An elaborate, custom popup
        var myPopup = $ionicPopup.show({
            template: '<input type="password" ng-model="data.wifi">',
            title: 'Enter Wi-Fi Password',
            subTitle: 'Please use normal things',
            scope: $scope,
            buttons: [
                { text: 'Cancel' },
                {
                    text: '<b>Save</b>',
                    type: 'button-positive',
                    onTap: function(e) {
                        if (!$scope.data.wifi) {
                            //don't allow the user to close unless he enters wifi password
                            e.preventDefault();
                            } else {
                            return $scope.data.wifi;
                        }
                    }
                },
            ]
        });
        myPopup.then(function(res) {
            console.log('Tapped!', res);
        });
        $timeout(function() {
            myPopup.close(); //close the popup after 3 seconds for some reason
        });
    };
});

A: you can use ionic modal for this purpose checkout this link for a documentation
http://ionicframework.com/docs/api/service/$ionicModal/
and you can find alot of examples in codepen


text:
Q: T-student distribution. can't find the numbers in the table I need to know the probability of P(-1.22<t7<1.92).
I only know how to do that when both number are equal, like P(y<t7<y).
Plus: in the t-student table, t7 line, there isn't either -1.22 or 1.92.
Could you help me, please?


text:
Q: Add nested object to existing logic in Python Below is the dataframe
df = pd.DataFrame([['xxx xxx','specs','67646546','TEST 123','United States of America']], columns = ['name', 'type', 'aim', 'aimd','context' ])

I am trying to add a object 'aimd' under 'data'.
Below is the format
{
    "entities": [{
            "name": "xxx xxx",
            "type": "specs",
            "data": {
                "attributes": {
                    "aimd": {
                        "values": [{
                                "value": "xxxxx",
                                "source": "internal",
                                "locale": "en_Us"
                            }
                        ]
                    }
                },
                "contexts": [{
                        "attributes": {
                            "aim": {
                                "values": [{
                                        "value": "67646546",
                                        "source": "internal",
                                        "locale": "en_Us"
                                    }
                                ]
                            }
                        },
                        "context": {
                            "country": "United States of America"
                        }
                    }
                ]
            }
        }
    ]
}

A: It's just a matter of inserting an additional array:
import pandas as pd
import json

df = pd.DataFrame([['xxx xxx','specs','67646546','TEST 123','R12',43,'789S','XXX','SSSS','GGG','TTT','United States of America']], columns = ['name', 'type', 'aim', 'aimd','aim1','aim2','alim1','alim2','alim3','apim','asim','context' ])

exclude_list = ['name','type','aimd','context']

data = {'entities':[]}
for key,grp in df.groupby('name'):
    for idx, row in grp.iterrows():
        temp_dict_alpha = {'name':key,'type':row['type'],'data' :{'attributes':{},'contexts':[{'attributes':{},'context':{'country':row['context']}}]}}

        attr_row = row[~row.index.isin(['name','type'])]
        for idx2,row2 in attr_row.iteritems():
            if idx2 not in exclude_list:
                dict_temp = {}
                dict_temp[idx2] = {'values':[]}
                dict_temp[idx2]['values'].append({'value':row2,'source':'internal','locale':'en_Us'})
                temp_dict_alpha['data']['contexts'][0]['attributes'].update(dict_temp)

            if idx2 == 'aimd':
                dict_temp = {}
                dict_temp[idx2] = {'values':[]}
                dict_temp[idx2]['values'].append({'value':row2,'source':'internal','locale':'en_Us'})
                temp_dict_alpha['data']['attributes'].update(dict_temp)

        data['entities'].append(temp_dict_alpha)

print(json.dumps(data, indent = 4))

Output:
print(json.dumps(data, indent = 4))
{
    "entities": [
        {
            "name": "xxx xxx",
            "type": "specs",
            "data": {
                "attributes": {
                    "aimd": {
                        "values": [
                            {
                                "value": "TEST 123",
                                "source": "internal",
                                "locale": "en_Us"
                            }
                        ]
                    }
                },
                "contexts": [
                    {
                        "attributes": {
                            "aim": {
                                "values": [
                                    {
                                        "value": "67646546",
                                        "source": "internal",
                                        "locale": "en_Us"
                                    }
                                ]
                            },
                            "aim1": {
                                "values": [
                                    {
                                        "value": "R12",
                                        "source": "internal",
                                        "locale": "en_Us"
                                    }
                                ]
                            },
                            "aim2": {
                                "values": [
                                    {
                                        "value": 43,
                                        "source": "internal",
                                        "locale": "en_Us"
                                    }
                                ]
                            },
                            "alim1": {
                                "values": [
                                    {
                                        "value": "789S",
                                        "source": "internal",
                                        "locale": "en_Us"
                                    }
                                ]
                            },
                            "alim2": {
                                "values": [
                                    {
                                        "value": "XXX",
                                        "source": "internal",
                                        "locale": "en_Us"
                                    }
                                ]
                            },
                            "alim3": {
                                "values": [
                                    {
                                        "value": "SSSS",
                                        "source": "internal",
                                        "locale": "en_Us"
                                    }
                                ]
                            },
                            "apim": {
                                "values": [
                                    {
                                        "value": "GGG",
                                        "source": "internal",
                                        "locale": "en_Us"
                                    }
                                ]
                            },
                            "asim": {
                                "values": [
                                    {
                                        "value": "TTT",
                                        "source": "internal",
                                        "locale": "en_Us"
                                    }
                                ]
                            }
                        },
                        "context": {
                            "country": "United States of America"
                        }
                    }
                ]
            }
        }
    ]
}


text:
Q: Running time of an application in Visual Studio I am solving some algorithm problems in c# and running them as a console application.
To check for the efficiency of the applications I would like to see what their run times are.
Currently I am printing the time at the start of a program and at the end and calculating the time difference ,but is there a way to reduce Observer' effect ?
Some inbuilt tool/plugin  that I am not aware of ?

A: You should use the Stopwatch class, which is specifically designed to do that.
To avoid measuring the JIT time, you should also run each algorithm at least once before measuring anything so that the JIT has time to run.
When measuring the algorithms, you should run each one hundreds of times and take the average runtime.

A: The most important source of delay due to observer's effect is printing itself. Another potential delayer is debug message text formatting. So I suggest the following:

*

*If you can anticipate the number of loops and number of stages per
loop, create an array to store timing information. If not, use a
dynamic list.

*During execution, store time and aditional information in that array
or list.

*If possible, don't store messages along with time but codes, for
example 1=Stage 1, 2=Stage 2, etc.

*At the end of the execution, dump all the information to screen or file, and format messages as needed.

A: Use stopwatch class. Look at at the method below for an example.
using System.Diagnostics;

    public void yourAlgorithm()
        {

            Stopwatch timePerParse = Stopwatch.StartNew();
            /** -- TODO --**/

            timePerParse.Stop();
            Console.WriteLine(timePerParse.ElapsedMilliseconds);

        }


text:
Q: Stopping all processes with SIGTERM/heroku/discord.py bot My discord.py-rewrite bot is currently being hosted on heroku. It's been fine for these past few weeks until heroku started going haywire just a few hours ago. Why is this happening?
This is the full error
2020-08-26T22:31:28.999683+00:00 heroku[worker.1]: Relocating dyno to a new server
2020-08-26T22:31:29.006086+00:00 heroku[worker.1]: State changed from up to down
2020-08-26T22:31:29.008558+00:00 heroku[worker.1]: State changed from down to starting
2020-08-26T22:31:42.288485+00:00 heroku[worker.1]: Starting process with command `python skybot.py.py`
2020-08-26T22:31:42.917236+00:00 heroku[worker.1]: State changed from starting to up
2020-08-26T22:31:51.626938+00:00 app[worker.1]: Signed In
2020-08-26T22:32:16.991403+00:00 heroku[worker.1]: Stopping all processes with SIGTERM
2020-08-26T22:32:20.126043+00:00 heroku[worker.1]: Process exited with status 0
2020-08-27T03:16:41.956314+00:00 heroku[worker.1]: Stopping all processes with SIGTERM
2020-08-27T03:16:42.134827+00:00 heroku[worker.1]: Process exited with status 0

Have I ran out of hours already? Or is this just some common bug in the heroku deployment system. I never made any changes to the script btw. This just happened out of the blue.


text:
Q: MySQL explode comma separated string in another table? I have table :
id | name
1  | a,b,c
2  | b

in another table i want like this :
id | parent | name
1  |   1    | a
2  |   1    | b
3  |   1    | c
4  |   2    | b

Please help me how to get it done in MySQL


text:
Q: Datepicker in html I have a date fields in my Form and I want user to select the dates from the calendar. however I need to create a datepicker.Searched on net still cant find the best answers.Is it possible to have a date picker in html?

A: You can add a datepicker in html with one of HTML5 Input Types, but also (not supported in Internet Explorer), For example :

<form action="action_page.php">
        Birthday:
        <input type="date" name="bday">
        <input type="submit">
</form>

See DEMO from w3schools.com


text:
Q: Signing driver for x64 Windows, making my CA known to Windows - without test-signing How can I sign a driver for Windows Vista (and newer) using a certificate rooted in my own CA and make Windows aware that the particular certificate or the CA in which it is rooted is okay to load without enabling test-signing mode (bcdedit -set TESTSIGNING ON)?
Rationale: enabling test-signing means to enable it globally for anything. I don't want that. I want a fine-grained control over what runs. The driver isn't intended for broad use, hence I do not want to open up a huge hole in my security measures by enabling test-signing globally. As far as I'm aware, test-signing basically boils down to a check whether the driver is signed at all (not whether the certificate chain is alright with the Windows kernel).
Note: I am aware of the Kernel-Mode Code Signing Policy and its pitfalls, I am also aware how to test a driver with test-signing on etc etc, so no need to point these out. In fact I've done those things. All I am really interested in is registering my own certificate or the CA in which it is rooted in order to allow drivers signed with that to run. The local system certificate store (part of the registry, AFAIR), doesn't seem to be available this early in the boot process or doesn't get checked.


text:
Q: Не работает русский язык в debian Не работает русский язык в tmux, в screen работает русский язык на половину. Уже всё пробывал делать, стоит Debian 11, хостинг appletec.

A: После установки всех нужны пакетов зайдите в .bashrc и добавьте это строчку - export LC_ALL=ru_RU.UTF-8
Должно это выглядеть вот так:


text:
Q: How can I solve append issue for an image using ajax My first script provides to random image as you can see below

It works when I add some images like that

But when I add my second script which get images as you can see

Finally I try to use my dynamic images in my "slideshow div" but the effect does not work

A: You need to run $t('.slideshow').cycle after you have dynamically inserted your images. Also you need to append to the "slideshow" class and not the "firmShowCase" class.
See this jsFiddle I've created http://jsfiddle.net/davew9999/sgUeq/
HTML

JavaScript
var $t = jQuery.noConflict();

var newFirmDiv = $t('');
$t(".slideshow").append(newFirmDiv);

var anotherDiv = $t('');
$t(".slideshow").append(anotherDiv);

$t(function() {
    $t('.slideshow').cycle({
        fx: 'fade'
    });
});


text:
Q: Linkedin API Company Updates not returning 50 recents updates I am trying to fetch companies updates with this API
https://developer.linkedin.com/docs/company-pages#company_updates
I use Node.js with linkedin-js package module wrapper.
I found that I only got 5 posts from this company (id=3487133). But it shown in page, that it got more than 5 updates. How can I get all its posts updates ? Thanks.
Here is my code
var linkedin_client = require('linkedin-js')(appid, appsecret, url_callback)

var cid = 3487133;
var param = {
  token: {
    oauth_token_secret: <token_secret>,
    oauth_token: <token>
  },
  count: 50
}

//post
linkedin_client.apiCall('GET', '/companies/' + cid + '/updates', param, function(error, result) {
  console.log(result)
});

A: There is nothing wrong with your code.
From https://developer.linkedin.com/docs/company-pages#company_updates you can find that

Only the most recent 50 updates for events of type status-update will
  be returned.  For all other event types, the request will return all
  the updates within the past 20 days, or 250 total updates - whichever
  comes first.

Using Linkedin console (https://api.linkedin.com/v1/companies/3487133/updates) fo getting the updates for your company, its giving the same 5 posts. Rest of the posts in your page are 20 days + older.


text:
Q: How to Point a directory to open on Server IP address as URL on Apache Web Server? I am using Latest Ubuntu Linux and Apache2 Web server. I have made my Home directory as a Root directory of the Web server. Here I put multiple websites in different folders like
home/site1/
home/site2/

And they load on Browser like this
http://123.456.789.102/site1
http://123.456.789.102/site2

So now what I want to do is, I have one more directory as
home/mainsite/

And I want it to load when I directly use this URL in browser
http://123.456.789.102

Other thing about this site is, it is built using Symfony framework. So after configuration, the site will load using this URL
http://123.456.789.102/web

So next I have to do some configuration to remove /web from URL
I am not good at configuring Apache server files. So if anyone can guide me out, that would be very helpful.
Thanks in Advance

A: this should solve your problem, you should not use your IP/site directory, instead point a domain to that directory
some basic configuration
for main domain
main.conf file at /etc/apache2/sites-available/ directory wit
<VirtualHost *:80>
ServerName MAINDOMAIN.COM
DocumentRoot /home/mainsite/web
ServerAlias www.MAINDOMAIN.COM
<Directory /home/mainsite>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>

create a symlink to the site with this command
ln -s /etc/apache2/sites-available/main.conf /etc/apache2/sites-enabled/main.conf

for a subdomain
subdomain.conf at /etc/apache2/sites-available/
<VirtualHost *:80>
ServerName SUB.DOMAIN.COM
DocumentRoot /home/site1
ServerAlias www.SUB.DOMAIN.COM
<Directory /home/site1>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>

create a symlink for it.
ln -s /etc/apache2/sites-available/subdomain.conf /etc/apache2/sites-enabled/subdomain.conf

and finally restart apache2
service apache2 restart

this are just basics, take a look at links below for more information
Ubuntu Help
Ubuntu 11.04 server guide
Apache2 guide

edited after the comment of olivierw, thanks
hope it helped

A: You may use an alias here:
Alias /site1 "/home/site1"

<Directory "/home/site1">
    Options FollowSymlinks
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>