text:
Q: MultiLanguage - Logic error beginner I am using WIndows 8, and Visual Studio 2012 Metro. I need to add a DropDownList and make the user select languages. When the user selects a particular language i need all the Text values in the label to change to that particular language.
I followed this tutorial
I  R-CLick project added `APPGlobal_Resource` folder
I R-Clicked and added `APPGlobal_Resource` and created a Resource file called rss.resx
Then i duplicated this file and named it rss.fr.resx
I gave 2 values `String1` and `Hello` and `Bonjour` as values (in both files)
R-Click `dropdownlist` and `edit item`, and `ADD` and then gave `en-US` as `Name` and `value`as  `en-US` (same way i gave `en-fr`)
Then i set the Label property, `Data (Expression)` `Bindable property` to `Text` and `Expression Type` to `Resources`.

I gave the `Class Key` to `Res` and `Resource Key` to `String1`.

and i wrote the following code in Default.aspx.cs
 protected override void InitializeCulture()
        {
            base.InitializeCulture();
            String cult = Request["DropDownList1"];

            if (cult != null)
            {
                Culture = cult;
                UICulture = cult;
            }
        }

The drop down displays with en-US and en-fr but when i select it nothing changes. How can i resolve this ?

A: Not sure, but it can help:
System.Threading.Thread.CurrentThread.CurrentCulture =
    new System.Globalization.CultureInfo( cult );


text:
Q: angular error en el constructor Hola buenas no se porque me da este error en el constructor de mi heroes component, el error por lo visto esta aqui y no se porque, si dejo el constructor vacio si va, y esta todo exportado correctamente:
constructor(private heroeS:HeroesService) {
  this.heroesToDisplay = this.heroeS.getListaHeroes();
}

El error:
Error: [object Object]
Stack trace:
resolvePromise@webpack-internal:///./node_modules/zone.js/dist/zone.js:814:31
resolvePromise@webpack-internal:///./node_modules/zone.js/dist/zone.js:771:17
scheduleResolveOrReject/<@webpack-internal:///./node_modules/zone.js/dist/zone.js:873:17
ZoneDelegate.prototype.invokeTask@webpack-internal:///./node_modules/zone.js/dist/zone.js:421:17
onInvokeTask@webpack-internal:///./node_modules/@angular/core/esm5/core.js:4967:24
ZoneDelegate.prototype.invokeTask@webpack-internal:///./node_modules/zone.js/dist/zone.js:420:17
Zone.prototype.runTask@webpack-internal:///./node_modules/zone.js/dist/zone.js:188:28
drainMicroTaskQueue@webpack-internal:///./node_modules/zone.js/dist/zone.js:595:25
ZoneTask.invokeTask@webpack-internal:///./node_modules/zone.js/dist/zone.js:500:21
invokeTask@webpack-internal:///./node_modules/zone.js/dist/zone.js:1540:9
globalZoneAwareCallback@webpack-internal:///./node_modules/zone.js/dist/zone.js:1566:17

El componente
//HEROES COMPONENT
import { Component, OnInit } from '@angular/core';
import { HeroesService, HeroesInterface } from '../../services/heroes.service';
import { Router } from '@angular/router';

//26. OMITO PASOS QUE YA SE =>
@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {

  heroesToDisplay:HeroesInterface[];

  constructor(private heroeS:HeroesService) {
    this.heroesToDisplay = this.heroeS.getListaHeroes();
  }

  ngOnInit() {
    console.log('iniciando heroes');

  }

}

El servicio:
//HEROES SERVICE
import { Injectable } from '@angular/core';

export interface HeroesInterface{
  id:number,
  nombre:string,
  bio:string,
  img:string,
  aparicion:string,
  casa:string
}

@Injectable()
export class HeroesService {

  private lista_heroes:HeroesInterface[] = [
      {
        id:1,
        nombre: "Aquaman",
        bio: "El poder más reconocido de Aquaman es la capacidad telepática para comunicarse con la vida marina, la cual puede convocar a grandes distancias.",
        img: "assets/img/aquaman.png",
        aparicion: "1941-11-01",
        casa:"DC"
      },
      {
        id:2,
        nombre: "Batman",
        bio: "Los rasgos principales de Batman se resumen en «destreza física, habilidades deductivas y obsesión». La mayor parte de las características básicas de los cómics han variado por las diferentes interpretaciones que le han dado al personaje.",
        img: "assets/img/batman.png",
        aparicion: "1939-05-01",
        casa:"DC"
      },
      {
        id:3,
        nombre: "Daredevil",
        bio: "Al haber perdido la vista, los cuatro sentidos restantes de Daredevil fueron aumentados por la radiación a niveles superhumanos, en el accidente que tuvo cuando era niño. A pesar de su ceguera, puede \"ver\" a través de un \"sexto sentido\" que le sirve como un radar similar al de los murciélagos.",
        img: "assets/img/daredevil.png",
        aparicion: "1964-01-01",
        casa: "Marvel"
      },
      {
        id:4,
        nombre: "Hulk",
        bio: "Su principal poder es su capacidad de aumentar su fuerza hasta niveles prácticamente ilimitados a la vez que aumenta su furia. Dependiendo de qué personalidad de Hulk esté al mando en ese momento (el Hulk Banner es el más débil, pero lo compensa con su inteligencia).",
        img: "assets/img/hulk.png",
        aparicion: "1962-05-01",
        casa:"Marvel"
      },
      {
        id:5,
        nombre: "Linterna Verde",
        bio: "Poseedor del anillo de poder que posee la capacidad de crear manifestaciones de luz sólida mediante la utilización del pensamiento. Es alimentado por la Llama Verde (revisada por escritores posteriores como un poder místico llamado Starheart), una llama mágica contenida en dentro de un orbe (el orbe era en realidad un meteorito verde de metal que cayó a la Tierra, el cual encontró un fabricante de lámparas llamado Chang)",
        img: "assets/img/linterna-verde.png",
        aparicion: "1940-06-01",
        casa: "DC"
      },
      {
        id:6,
        nombre: "Spider-Man",
        bio: "Tras ser mordido por una araña radiactiva, obtuvo los siguientes poderes sobrehumanos, una gran fuerza, agilidad, poder trepar por paredes. La fuerza de Spider-Man le permite levantar 10 toneladas o más. Gracias a esta gran fuerza Spider-Man puede realizar saltos íncreibles. Un \"sentido arácnido\", que le permite saber si un peligro se cierne sobre él, antes de que suceda. En ocasiones este puede llevar a Spider-Man al origen del peligro.",
        img: "assets/img/spiderman.png",
        aparicion: "1962-08-01",
        casa: "Marvel"
      },
      {
        id:7,
        nombre: "Wolverine",
        bio: "En el universo ficticio de Marvel, Wolverine posee poderes regenerativos que pueden curar cualquier herida, por mortal que ésta sea, además ese mismo poder hace que sea inmune a cualquier enfermedad existente en la Tierra y algunas extraterrestres . Posee también una fuerza sobrehumana, que si bien no se compara con la de otros superhéroes como Hulk, sí sobrepasa la de cualquier humano.",
        img: "assets/img/wolverine.png",
        aparicion: "1974-11-01",
        casa: "Marvel"
      }
  ];

  constructor() {
    console.log('el servicio esta listo para usarse 2');

   }

   getListaHeroes():HeroesInterface[]{
    return this.lista_heroes;
  }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Intent: cannot proceed to next activity The intent keeps showing the same activity and does not proceed to the next activity according to the counter that is stored in a firebase real-time database. The reason why there is a counter is that I want to reuse the EditPetDetail activity.
I have tried a couple of setFlags, removeExtra in the EditPetDetail activity, finish(), looking at the android manifest file and it still shows the same activity layout after proceeding into the appropriate function.
As for the removeExtra, I wrote the code after transferring the data of the extras into the variables.
This is the function inside the Device Activity.
    public void EditPet(){
        Intent intent = new Intent(this, EditPetDetail.class);
        intent.putExtra("dbDevice", deviceno);
        intent.putExtra("dbName", nameID);
        intent.putExtra("dbAge", ageID);
        intent.putExtra("dbWeight", weightID);
        intent.putExtra("dbType", typeID);
        intent.putExtra("dbCounter", counter);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }

This is the function inside the EditPetDetail Activity.
    public void MainPage(){
        Toast.makeText(getApplicationContext(), "123", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    public void PetDetail(){
        Toast.makeText(getApplicationContext(), "Nononope", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(this, pet_detail.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }

This is the android manifest activity names.
 <activity android:name=".EditPetDetail"></activity>
 <activity android:name=".Device">
     <intent-filter>
         <action android:name="android.intent.action.MAIN" />
         <category android:name="android.intent.category.LAUNCHER" />
     </intent-filter>
 </activity>
 <activity android:name=".pet_detail" />
 <activity android:name=".MainActivity" />

I expected the activity to proceed to the different functions based on whether the counter is 0 or 1, but it didn't work. I also used a toast to make sure that it is going to the right function, but in the end after the animation, it just showed me the same activity without any fields in the EditText.


text:
Q: Jetpack Compose saving state on orientation change I am using Android Jetpack's Compose and have been trying to figure out how to save state for orientation changes.
My train of thought was making a class a ViewModel. As that generally worked when I would work with Android's traditional API.
I have used remember {} and mutableState {} to update the UI when information has been changed.
Please validate if my understanding is correct...
remember = Saves the variable and allows access via .value, this allows values to be cache. But its main use is to not reassign the variable on changes.
mutableState = Updates the variable when something is changed.
Many blog posts say to use @Model, however, the import gives errors when trying that method.
So, I added a : ViewModel()
However, I believe my remember {} is preventing this from working as intended?
Can I get a point in the right direction?
@Composable
fun DefaultFlashCard() {

    val flashCards = remember { mutableStateOf(FlashCards())}

    Spacer(modifier = Modifier.height(30.dp))

    MaterialTheme {

        val typography = MaterialTheme.typography
        var question = remember { mutableStateOf(flashCards.value.currentFlashCards.question) }

        Column(modifier = Modifier.padding(30.dp).then(Modifier.fillMaxWidth())
                .then(Modifier.wrapContentSize(Alignment.Center))
                .clip(shape = RoundedCornerShape(16.dp))) {
            Box(modifier = Modifier.preferredSize(350.dp)
                    .border(width = 4.dp,
                            color = Gray,
                            shape = RoundedCornerShape(16.dp))
                    .clickable(
                            onClick = {
                                question.value = flashCards.value.currentFlashCards.answer })
                    .gravity(align = Alignment.CenterHorizontally),
                    shape = RoundedCornerShape(2.dp),
                    backgroundColor = DarkGray,
                    gravity = Alignment.Center) {
                Text("${question.value}",
                        style = typography.h4, textAlign = TextAlign.Center, color = White
                )
            }
        }

        Column(modifier = Modifier.padding(16.dp),
                horizontalGravity = Alignment.CenterHorizontally) {

            Text("Flash Card application",
                    style = typography.h6,
                    color = Black)

            Text("The following is a demonstration of using " +
                    "Android Compose to create a Flash Card",
                    style = typography.body2,
                    color = Black,
                    textAlign = TextAlign.Center)

            Spacer(modifier = Modifier.height(30.dp))
            Button(onClick = {
                flashCards.value.incrementQuestion();
                question.value = flashCards.value.currentFlashCards.question },
                    shape = RoundedCornerShape(10.dp),
                    content = { Text("Next Card") },
                    backgroundColor = Cyan)
        }
    }
}

data class Question(val question: String, val answer: String) {
}

class FlashCards: ViewModel() {

    var flashCards = mutableStateOf( listOf(
            Question("How many Bananas should go in a Smoothie?", "3 Bananas"),
            Question("How many Eggs does it take to make an Omellete?", "8 Eggs"),
            Question("How do you say Hello in Japenese?", "Konichiwa"),
            Question("What is Korea's currency?", "Won")
    ))

    var currentQuestion = 0

    val currentFlashCards
        get() = flashCards.value[currentQuestion]

    fun incrementQuestion() {
        if (currentQuestion + 1 >= flashCards.value.size) currentQuestion = 0 else currentQuestion++
    }
}

A: UPDATE:
There are 2 built-in ways for persisting state in Compose:

*

*remember: exists to save state in Composable functions between recompositions.

*rememberSaveable: remember only save state across recompositions and doesn't handle configuration changes and process death, so to survive  configuration changes and process death you should use remeberSaveable instead.
But there are some problems with rememberSaveable too:

*

*Supports primitive types out of the box, but for more complex data, like data class, you must create a Saver to explain how to persist state into bundle,

*rememberSaveable uses Bundle under the hood, so there is a limit of how much data you can persist in it, if data is too large you will face TransactionTooLarge exception.
with above said, below solutions are available:

*

*setting android:configChangesin Manifest to avoid activity recreation in configuration changes. (not useful in process death, also doesn't save you from being recreated in Wallpaper changes in Android 12)

*Using a combination of ViewModel + remeberSaveable + data persistance in storage
=======================================================

Old answer

Same as before, you can use Architecture Component ViewModel to survive configuration changes.
You should initialize your ViewModel in Activity/Fragment and then pass it to Composable functions.
class UserDetailFragment : Fragment() {

    private val viewModel: UserDetailViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return ComposeView(context = requireContext()).apply {
            setContent {
                AppTheme {
                    UserDetailScreen(
                        viewModel = viewModel
                    )
                }
            }
        }
    }
}

Then your ViewModel should expose the ViewState by something like LiveData or Flow
UserDetailViewModel:
class UserDetailViewModel : ViewModel() {
    private val _userData = MutableLiveData<UserDetailViewState>()
    val userData: LiveData<UserDetailViewState> = _userData

    // or

    private val _state = MutableStateFlow<UserDetailViewState>()
    val state: StateFlow<UserDetailViewState>
        get() = _state

}

Now you can observe this state in your composable function:
@Composable
fun UserDetailScreen(
    viewModel:UserDetailViewModel
) {
    val state by viewModel.userData.observeAsState()
    // or
    val viewState by viewModel.state.collectAsState()

}

A: There is another approach to handle config changes in Compose, it is rememberSaveable. As docs says:

While remember helps you retain state across recompositions, the state is not retained across configuration changes. For this, you must use rememberSaveable. rememberSaveable automatically saves any value that can be saved in a Bundle. For other values, you can pass in a custom saver object.

It seems that Mohammad's solution is more robust, but this one seems simpler.


text:
Q: NSTimeZone list contiains duplicate time zones? When listing all time zones returned by [NSTimeZone knownTimeZoneNames] on an iPhone 4, there are some that appear to be functional duplicates.  They're listed largely by city.  For example, I would expect America/Chicago and America/Indiana/Knox to both equate to the Central Time Zone (see here for a time zone reference).  Am I missing a difference between them?  Or is it just Apple being user-friendly by letting the user choose their zone by city?

A: Indiana is odd when it comes to time zones.
Keep in mind that if a particular area was ever different from the areas around it, it needs a new time zone defined, because you could ask for a time at any point in history.
Different areas of Indiana have moved to different time zones in the past to coincide with major metropolis areas close to them (Louisville and Chicago in particular), and some of them even started or stopped observing daylight savings time which made them "in sync" with places near them only part of the year.
All of this means more time zones in ios in order to cover all of the different scenarios, both now, and in the past.


text:
Q: How to compile and control PUG files with Express & GULP We are trying to set up GULP file to serve PUG files into HTML and put them into static dist folder.
Here are our files:
https://github.com/ShooX512/gulp-testing/
This is how we control PUG so far:
app.set("views", path.join(__dirname, "./dist/"));

but because of the fact that GULP generates HTML files in dist we have added this:
app.use(
  "./dist",
  express.static(path.join(__dirname, "./dist"), { maxAge: "30 days" })
);

This unfortunately doesn't work.
My main questions are:
Which version of the code should be used and when?
How to pass data to generated HTML files in dist folder? (Originally PUG)
Do we need GULP to compile PUG at all if we use:
app.set("view engine", "pug");
app.set("views", path.join(__dirname, "./dist/"));


text:
Q: Mobile user profile page sort selectors stop working after first change The drop-down menus used to select user profile section sorting / display modes in the mobile view stop working after the first click:

I've tested this both in Firefox on my desktop, and in Chrome on my Android tablet, and can confirm that it happens on both.
The problem is actually pretty simple: the event handler that makes the menu work is attached directly to the menu at page load time.  However, the handler itself reloads the entire section, including the menu, via AJAX, and does not reattach itself to the new menu.
The fix is also pretty simple: just replace this line in user.js, in the StackExchange.user.init() method:
$('.user-panel-subtabs select').on('change', function() {

with:
$('.user-panel-subtabs select').live('change', function() {

or, better yet (to avoid the deprecated jQuery.live() method):
$(document).on('change', '.user-panel-subtabs select', function() {

Ps. This bug is also masking another, related one: if the same section's sorting / display mode is changed more than once between page loads, on the next reload the section content will (correctly) match whatever was last selected, but the drop-down menu will show the first selection made after the previous page load.  This appears to be a server-side issue, so I cannot diagnose it further.

Pps. I've developed a client-side fix for the event handler issue, and a partial fix for the sync issue, which are included in the Stack Overflow Unofficial Patch user script as of version 1.24.  Alas, very few (if any) mobile browsers can run user scripts, so the practical value of the fix is limited.


text:
Q: Checkbox values fetching using Jquery I have multiple checkboxes. The users can select either one or more than one. So, I have to get the values of those checked boxes.

                            @foreach($destination as $dest)
                            {{$dest->destination}}
                                <input  type="checkbox" name="dest_val" value="{{$dest->id}}">

                            @endforeach

By the way I am using Laravel.So, in the Jquery, I am writing this:
   $(document).on('click','#desti',function () {

           var destination = $("input[name='dest_val']:checked").val()
               console.log(destination);

       });

But, it is not giving me the correct values. When I click on first checkbox it gives value = 1, which is correct and when I click on 2 it gives 2 which is correct. So, when 1 is checked and I check 2 then, I am getting two one's added to the previous 1, which makes 1(3)/ 1 times 3 and I also get 1 two. So, what I want is when I check 2 I get only 2 and not anymore ones.
This kind of thing is happening in vice-versa too. Can anyone help?

A: You cannot reuse id properties on DOM elements without getting odd results like this. Try using a unique id for each checkbox or perhaps a class name.
You're also going to want to give the checkboxes a unique name.
Here is an example of using a class name:
HTML

        @foreach($destination as $dest)
            {{$dest->destination}}
                <input type="checkbox" value="{{$dest->id}}">

       @endforeach

JS
$(document).on('click','.checkbox-label',function () {
    var destination = $(this).find('input[type="checkbox"]').val();
    console.log(destination);
});


text:
Q: How to change default secrets.yml file in Rails 5 I accidentally uploaded my secrets.yml file to Github.  I changed my credentials and moved it to a new secrets_final.yml file that I've property setup in gitignore.  Problem now is unless I hardcode credentials, the environment variables don't seem to pull from this new file.
How do I change default secrets location?

A: I figured out how to get gitignore to stop tracking a file as when I added it to gitignore file, it still tracked file because it was cached. No need to change defaults secrets.yml - just remove cache and use same file.  Answer is here: https://stackoverflow.com/a/11451731/5551783


text:
Q: Are the only eigenvalues of an operator $T^k$ the $\lambda_n^k$? If I have an operator T which has eigenvalues $(\lambda_n)_{n \in \mathbb{N}}$, I understand that $\lambda_n^k$ are eigenvalues for $T^k$. But how to show that these are the only eigenvalues? Is this even true?

A: Over a field which is not algebraically closed, this is false. Consider
$$A=\begin{bmatrix} 0 & -1 \\ 1 & 0\end{bmatrix}\in M_2(\mathbb R).$$
Then $A^2=-I$, which has only the eigenvalues $-1$, but $A$ has no eigenvalues.
But over an algebraically closed field, this is true for operators on finite-dimensional spaces by the Jordan decomposition: squaring the matrix applies to each Jordan block separately.


text:
Q: Curry-Howard isomorphism definitions in Coq using fun I'm having some issues with defining in Coq, more specifically when defining using the CHI. I have managed to gain the understanding of basic principals but when I try to define this"
((A -> (A -> C)) * ((A -> C) -> A)) -> C :=

I get nowhere due to the fact it keeps telling me:
"Error: The type of this term is a product while it is expected to be "C".
I have already tried the usual tactics I have used earlier in my script and I'm convinced this has to be solved using the same methods (fun) however everything I seem to be trying ends in that error message. Any tips?

A: It seems you are defining a function that takes as input:

*

*a function of type A -> (A -> C): given an object of type A, it gives back a function of type A -> C.

*a function of type (A -> C) -> A: given a function of type A -> C, it gives back an object of type A.

You are trying to build an object of type C which I don't see how you will managed to do it. However you can build an object of type A by combining the two functions you have as input.
Hope it helps,
V.


text:
Q: Datastax spark cassandra connector with RetryPolicy to write DF to cassandra table I am trying to write a spark Dataframe to cassandra with consistency level "EACH_QUORUM". My code looks like below:
val sparkBuilder = SparkSession.builder().
  config(cassandraHostPropertyProperty, cassandraHosts).
  config(cassandraAuthUsernameProperty, CASSANDRA_AUTH_USER_KEY).
  config(cassandraAuthPassProperty, CASSANDRA_AUTH_PASS_KEY).
  config(cassandraIsSSLEnabledProperty, isSSLEnabled)...
  getOrCreate();

Below is the code to write DF:
df.write.cassandraFormat(tableName, keySpaceName)
    .mode(SaveMode.Append)
    .options(Map(
      WriteConf.ParallelismLevelParam.name -> parallelism_Level.toString,
      WriteConf.BatchSizeRowsParam.name -> rowsInBatch.toString
    ))
    .save()

I want to add a retry policy, so that if one of the datacenters in down, write downgrades consistency to LOCAL_QUORUM.
I am aware that datastax has a class MultipleRetryPolicy.scala which I should extend, override methods to add custom logic and use it's instance in cassandra conf.
How can I apply this policy to my sparksession or save operation? Is there any other way in scala with or without using RetryPolicy for achieving my requirement?

A: You don't want MultipleRetryPolicy, you're after DowngradingConsistencyRetryPolicy which isn't part of the spark driver, so doing this as part of driver settings is out unless you port the policy over to scala.
What you can do is wrap your query execution in a try and catch the UnavailableException then just re-try with a lower consistency by changing the output.consistency.level parameter.


text:
Q: Color lines in plotly r separately from markers I am trying to find a way to maintain the color of the line in my plotly graph, even if the marker colors change. I will explain... an example dataset:
mtcars$vs<-as.factor(mtcars$vs)
mtcars$gear<-as.factor(mtcars$gear)
mtcars$Date<-sample(seq(as.Date('2016/01/01'), as.Date('2018/01/01'), by="day"), 32)

I made a plot that I want:
pal <- c("red", "blue", "green")

mtcars %>%
  group_by(vs) %>%
  mutate(fit = fitted(loess(mpg ~ as.numeric(Date))))%>%
  plot_ly(x = ~Date,
          colors=pal, showlegend = T) %>%
  add_markers( y = ~mpg, color= ~vs, alpha = 0.4) %>%
  add_lines(y = ~fit, color = ~vs,line=list(width=4), colors=pal) %>%
  layout(xaxis = list(title="Date"), title="All")

which gives me

When I change the marker input like:
mtcars %>%
  group_by(vs) %>%
  mutate(fit = fitted(loess(mpg ~ as.numeric(Date))))%>%
  plot_ly(x = ~Date,
          colors=pal, showlegend = T) %>%
  add_markers( y = ~mpg, color= ~gear, alpha = 0.4) %>%
  add_lines(y = ~fit, color = ~vs,line=list(width=4), colors=pal) %>%
  layout(xaxis = list(title="Date"), title="All")

But then the line colors also change, I would like them to stay green en red..

I have tried to put "colors" on different locations in the script. I also saw posts where they added add_trace and I tried different things with filtering the data in add_trace, but it gave an error so I am not doing it the right way..
Could anyone help me? Would appreciate it a lot!

A: Found it! Really a bit silly really, just used the wrong color code:
df1<-mtcars%>%
  filter(vs=="0")%>%
  mutate(fit1 = fitted(loess(mpg ~ as.numeric(Date))))

df2<-mtcars%>%
  filter(vs=="1")%>%
  mutate(fit2 = fitted(loess(mpg ~ as.numeric(Date))))

  plot_ly(mtcars, x = ~Date,
          showlegend = T) %>%
  add_markers( y = ~mpg, color= ~vs) %>%
  add_lines(data=df1, y = ~fit1, line = list(color = 'rgb(22, 88, 229)')) %>%
  add_lines(data=df2, y = ~fit2, line = list(color = 'rgb(226, 124, 6)')) %>%
  layout(xaxis = list(title="Date"))

  plot_ly(mtcars, x = ~Date,
          showlegend = T) %>%
    add_markers( y = ~mpg, color= ~gear) %>%
    add_lines(data=df1, y = ~fit1, line = list(color = 'rgb(22, 88, 229)')) %>%
    add_lines(data=df2, y = ~fit2, line = list(color = 'rgb(226, 124, 6)')) %>%
    layout(xaxis = list(title="Date"))

Must be a quicker way to do it, but at least it works :)


text:
Q: KeyEvent doesn't understand ENTER key I'm creating a notepad using java.there seems to be a small problem.Java doesnt get the line of the code that has a condition concerning ENTER key.It understands ctrl and Alt.but not enter.just skips that part! what can I do?`
if( !e.isControlDown() && !e.isAltDown() && e.getKeyCode() != KeyEvent.VK_ENTER)
        {
            frame.wholeText.linesList.get(frame.cursor.j).chars.add(frame.cursor.i,c);
            frame.cursor.i += 1 ;
            System.out.println("Entered");
            charMetric = frame.getFontMetrics( frame.getFont() ).charWidth(c) ;
            frame.cursor.setX( frame.cursor.getX() + charMetric );

        }`

PS : It should not enter this condition when I press ENTER but it does.
PS2:It is in KeyTyped part of the code.

A: The documentation for KeyEvent.getKeyCode() is pretty clear:

Returns: the integer code for an actual key on the keyboard. (For KEY_TYPED events, the keyCode is VK_UNDEFINED.)

Conversely, KeyEvent.getKeyChar() says:

KEY_PRESSED and KEY_RELEASED events are not intended for reporting of character input. Therefore, the values returned by this method are guaranteed to be meaningful only for KEY_TYPED events.

KEY_PRESSED and KEY_RELEASED events generate a KeyEvent with a valid keyCode, but no keyChar.  KEY_TYPED events are the opposite:  they generate a KeyEvent with a valid keyChar, but the keyCode is always undefined.
You are checking the value of getKeyCode() for a KEY_TYPED event, so the keyCode will always be undefined.
Either use e.getKeyChar() != '\n' or perform your keyCode check in a keyPressed method.


text:
Q: How can I use opencv python cv2.xfeatures2d.SIFT as imput for cv2.calcOpticalFlowPyrLK? I made a stabilizer for videos and now I'm trying to compare my algorithm with others, so I wanted to implement the sift and pass the keypoints to the optical flow algorithm.
sift = cv2.xfeatures2d.SIFT_create()

then
frame.features = sift.detect(frame_img_gray,None)
new_features, _, _ = cv2.calcOpticalFlowPyrLK(prev_frame_img, frame_img, prev_frame.features, None, **lk_params)
        new_features_for_validation, _, _ = cv2.calcOpticalFlowPyrLK(frame_img, prev_frame_img, new_features, None,**lk_params)

So I get this message from the compiler:
 new_features, _, _ = cv2.calcOpticalFlowPyrLK(prev_frame_img, frame_img, prev_frame.features, None, **lk_params)
TypeError: prevPts is not a numpy array, neither a scalar

A: You can manually reshape SIFT output to be suitable for cv2.calcOpticalFlowPyrLK:
LK_pts=np.empty((0,1,2), np.float32)
for pts  in prev_frame.features:
    x, y = pts.pt
    LK_pts=np.append(LK_pts,np.array([[[x,y]]],dtype=np.float32),axis=0)


text:
Q: Only echo item in foreach with highest value I am trying to get the highest number from a set of SKUs in WordPress. I have the below code which gets a list of all SKUs. I am then only showing the ones which contain the string 'BUR' and then I am using explode to trim the output. Based on the below what is the best method?
Example Data:
ABB-0001-1
ABB-0002-1
ABB-0003-1
BUR-0001-1
BUR-0002-1
BUR-0003-1

Current Code:
<?php
$args = array(
    'post_type' => array('product'),
    'posts_per_page' => -1
);

$wcProductsArray = get_posts($args);

if (count($wcProductsArray)) {
    foreach ($wcProductsArray as $productPost) {
        $productSKU = get_post_meta($productPost->ID, '_sku', true);
        $productTitle = get_the_title($productPost->ID);
            if (strpos($productSKU, 'BUR') !== false) {
                $s = explode("-",$productSKU);
                echo '
' . $s[1] . '
';
            }
    }
}
?>

Current Output:
0003
0002
0001

Desired Output:
0003

A: Technically, this is more of a general PHP question rather than a WordPress question which should be on Stack Overflow instead.
To echo only the highest value from your array, try storing your items ($s[1]) into an array instead and then use max(). Something like this:
$args = array(
    'post_type' => array('product'),
    'posts_per_page' => -1
);

$wcProductsArray = get_posts($args);
$skuList = array();

if (count($wcProductsArray)) {
    foreach ($wcProductsArray as $productPost) {
        $productSKU = get_post_meta($productPost->ID, '_sku', true);
        $productTitle = get_the_title($productPost->ID);
            if (strpos($productSKU, 'BUR') !== false) {
                $s = explode("-",$productSKU);
                // echo '
' . $s[1] . '
';
                $skuList[] = $s[1];
            }
    }
}

echo( max($skuList) );

I don't have a WooCommerce setup right now to validate it, so you'll need to confirm that it works or play around with it.


text:
Q: Django - Can two or more templates be extended by one template? Let's say there are base_a.html, base_b.html, a.html, b.html, c.html.
a.html extends base_a.html and b.html extends base_b.html.
And c.html has to extend both base_a.html and base_b.html.
It will be easier to understand this situation if you think base_a.html contains reply functionalities and base_b.html contains search functionalities.
Can I use multiple inheritance in Django template?
Or do I have to use include instead of extends?

A: Yes you can extend different or same templates.
For example:
{% extends "base.html" %}
{%     block content     %}

Content goes here

{% include 'base.html' %}
{% endblock %}

A: As stated at the docs,

If you use {% extends %} in a template, it must be the first template tag in that template.

That suggests that an {% extends %} tag cannot be placed in the second line, that is, you cannot have two {% extends %} tags.
Your case can easily be solved with {% include %} tags. For example:
In a.html:
{% include 'base_a.html' %}

In b.html:
{% include 'base_b.html' %}

In c.html:
{% include 'base_a.html' %}
{% include 'base_b.html' %}

Of course, base_a.html and base_b.html should only contain the specific block you want to reuse, not a full HTML template.


text:
Q: jquery plugins for truncating long text string by container width/height As the title says, I want to truncate user-input text string based on the width and height of a designated container. My specification is to truncate the string, display some message like Read More at the end and when user clicks on it, the text slides down.
UPDATE: Ah! Forgot one thing. It should handle multi-byte characters as well.
Can somebody throw some light on what options do I have? jQuery plugins or some nifty jquery snippet?
Thanks and Regards

A: jQuery Expander Plugin:
HTML:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
    incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
    exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor.

Reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
    Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
    officia deserunt mollit anim id est laborum.

Javascript:

Source:
http://plugins.learningjquery.com/expander/index.html
See demo here:
http://plugins.learningjquery.com/expander/demo/index.html
Good luck ask me if you need clarifications!


text:
Q: query json data from oracle 12.1 having fields value with "." I have a table that has JSON data stored and I'm using json_exists functions in the query. Below is my sample data from the column for one of the rows.
{"fields":["query.metrics.metric1.field1",
           "query.metrics.metric1.field2",
           "query.metrics.metric1.field3",
           "query.metrics.metric2.field1",
           "query.metrics.metric2.field2"]}

I want all those rows which have a particular field. So, I'm trying below.
SELECT COUNT(*)
  FROM my_table
 WHERE JSON_EXISTS(fields, '$.fields[*]."query.metrics.metric1.field1"');

It does not give me any results back. Not sure what I'm missing here. Please help.
Thanks

A: You can use @ operator which refers to an occurrence of the array fields such as
SELECT *
  FROM my_table
 WHERE JSON_EXISTS(fields, '$.fields?(@=="query.metrics.metric1.field1")')

Demo
Edit : The above case works for 12R2+, considering that it doesn't work for your version(12R1), try to use JSON_TABLE() such as
SELECT fields
  FROM my_table,
  JSON_TABLE(fields, '$.fields[*]' COLUMNS ( js VARCHAR2(90) PATH '$' ))
 WHERE js = 'query.metrics.metric1.field1'

Demo

A: I have no idea how to "pattern match" on the array element, but just parsing the whole thing and filtering does the job.
with t(x, json) as (
  select 1, q'|{"fields":["a", "b"]}|' from dual union all
  select 2, q'|{"fields":["query.metrics.metric1.field1","query.metrics.metric1.field2","query.metrics.metric1.field3","query.metrics.metric2.field1","query.metrics.metric2.field2"]}|' from dual
)
select t.*
from t
where exists (
  select null
  from json_table(
    t.json,
    '$.fields[*]'
    columns (
      array_element varchar2(100) path '$'
    )
  )
  where array_element = 'query.metrics.metric1.field1'
);

In your code, you are accessing the field "query.metrics.metric1.field1" of an object in the fields array, and there is no such object (the elements are strings)...


text:
Q: SVN update not working after SVN relocate I have recently migrated my SVN repository from SERVER1 to SERVER2.

*

*installed SVN on SERVER2.

*used svnrdump utility to dump the repository.

*used svndump load utility to load the dump file to new svn server.

I checked out a working  copy WC from path http://SERVER1/project1/data from SERVER1 svn.
Note one thing here:

*

*When I took dump, SVN revision on SERVER1 was 12345.

*When I checked out WC , SVN revision was 13456.

Now, using relocate from tortoise svn on windows, I have relocated WC to SERVER2 svn to path http://SERVER2/project1/data.
Relocation is successfull.
After this, I am trying to check-in changes which were made from rev-12345 till rev-13456 to  http://SERVER2/project1/data.
But, here is what is happening:

*

*Commit operation does not show any files to be committed.

*Check for modification does not show any changes.

*SVN Update shows error 'No Such Revision: 13456'.

*I changed a file which existed on WC and on http://SERVER2/project1/data as well, and tried to commit it. Here also it gives 'No Such Revision: 13456'.

I was expecting that when WC at rev-13456 from SERVER1 will be relocated to  http://SERVER2/project1/data at rev-12345 from SERVER2, it will show all the differences which were made between these two revisions.
NOTE: I am trying above because SERVER1 will be shutdown in some time. As of now, both repositories exist. SERVER1 is still being used by people and SERVER2 is to be kept up-to-date with SERVER1.

A: Because you checked out your working copy at a later revision than what exists on the server you relocated to, it has no reference point to calculate changes.  This method of updating SERVER2 will not work.  You have two options:

*

*To properly update SERVER2 with all revisions that are missing, you must do a partial dump/load of the remaining revisions.  svnadmin dump repo_path -r 12346 --incremental, then load on new server.  It will dump only revisions for 12346 forward.  This will only work if you have not added other revisions to SERVER2 that were not part of SERVER1.

*If you don't care about the intervening revision history and just want to dump all the changes in that time into the new server as 1 revision, do a fresh check out from the new server first.  Then copy all changes over from your WC from SERVER1 into this WC of SERVER2 and commit.
The first option is better and probably even less work depending on how complicated the changes are.


text:
Q: how to send a value via tcp in rails? I am developing rails app and following are the things that i have done and i need to do.

*

*I am using rails for iphone app and i have an api for sending the values to the server.

*When a user sends the value to the server, the value has to be stored in db and i need to show the values to the other user.

*The other user should listen to the tcp server and the value should be received by that user.

*I have read few examples from https://www6.software.ibm.com/developerworks/education/l-rubysocks/l-rubysocks-a4.pdf and few other examples but i do not know how to proceed.

Please help me.

A: You can just use plain http (or https) to communicate with iphone app.


text:
Q: GrantAspNetServiceAccountAccessAction failed when install CRM 2015 When I install MSCRM 2015, I have met the problem
Microsoft.Crm.Setup.Server.GrantAspNetServiceAccountAccessAction failed
"The parameter is incorrect"
Microsoft.Crm.Setup.Server.GrantAspNetServiceAccountAccessAction failed

Our team has used the solution mentioned in Unable to install crm 2013 on server 2012, and the installed is performed by domain administrator account, but still the above problem exists.
We have checked the OU, there are no "Account Unknown" entries in AD.

A: Finally, We managed to solve the problem. The cause is due to the customer's AD version. The customer has 4 AD servers.
One of the AD servers is on Window 2008 which we thought fulfill the AD requirement for MSCRM2015. However, the functional levels of the AD is actually window 2003 as it takes the lowest function level version from other AD servers even it has the higher version. The pre-requisite for MSCRM2015 is that AD is window 2008 and above therefore it gives the error.


text:
Q: servor error in loging while allready loging in another window throwing server error, in
1st tab situation login and logout and
2.login again in another tab,
while trying to login in 1st again throwing servor error
https://apparel-uk.localhost:9002/en/j_spring_security_check
This error is because of the invalid CSRF token which is not in match with the session's csrf token.
how to hadle this .


text:
Q: How to compile PushNotifications code for ios only not for android in Titanium I am using Push-notifications code its working fine for ios but because of that not running in Android is there any way so that I can put any condition so that that particular code compile/run for ios and for android skip that particular code?

A: try Titanium.Platform.osname != "android"
or Titanium.Platform.osname == "iphone"
you can find more options here


text:
Q: Bash PS1 Doesn't Evaluate Variables I'm trying to set my PS1 prompt to
/usr/local/src mario

So I've used the following code inside of .bash_profile:
export PS1=" \w \u\[$(tput sgr0)\]"

And I end up with:
 \w \u\[$(tput sgr0)\]

Ideas?
I can use string concatenation to get what I want but that seems very odd that I need to do that.

A: Your shell is likely not bash. Change it with chsh.
Also, there's a problem with part of the $PS1 value:
PS1=" \w \u\[$(tput sgr0)\]"

The $(...) will be evaluated when you set PS1, but just that one time.  If you would like to execute tput sgr0 every time the prompt displays, use single quotes:
PS1='\w \u\[$(tput sgr0)\] \$ '

(I have also moved the initial space from the start to the end of the value and added \$ which will make the prompt and command line more readable.
You could also set
PS1="\w \u \$ "

and then set
PROMPT_COMMAND="tput sgr0"

to have tput sgr0 execute before displaying every prompt (I don't know if it makes sense to do this as I don't quite know what it does, but the facility for it is there).
Notice that neither PS1 nor PROMPT_COMMAND needs to be exported as it only makes sense to set them for the current shell session.


text:
Q: Write to database with Read only access [TSQL Stored Procedure] Situation:
I have various users that has been allowed READ ONLY access to a database.
Is it possible to INSERT rows to database via Stored Procedure using a range in Excel?
If yes, Can anyone please assist me with a sample VBA or SQL script?

A: I am sorry to be the bringer of bad news, however the work-around you want cannot be done on T-SQL. from official Microsoft documentation

" Permissions are not required to run the EXECUTE statement. However, permissions are required on the securables that are referenced within the EXECUTE string. For example, if the string contains an INSERT statement, the caller of the EXECUTE statement must have INSERT permission on the target table..."


text:
Q: How to open local file or url in Tor browser? I've just installed Tor-browser and I want to make it default system browser but can't because it can't do simple things like opening local files or urls.
When I enter in terminal:
torbrowser-launcher duck.com

It opens the browser on the default page and ignore my url, but torbrowser-launcher --help say:
usage: torbrowser-launcher [-h] [--settings] [url [url ...]]

positional arguments:
  url         URL to load

I've tried torbrowser-launcher url duck.com but it also doesn't work.

A: Give up the absolute path for "start-tor-browser" with --detach followed by URL
Something like;
'../tor-browser_en-US/Browser/start-tor-browser' --detach www.example.com


text:
Q: How to save confidential data on iOS? Keychain or Outh2? Thanks. As you know many apps use keychain to save user login name and password, but is it really safe? especially on device jail break mode. So another solution is to use Outh2 protocol to save those confidential infomation on server side which needs many changes on both client and server side (for my app).
How do you guys handle this tough issue?  Anyone who knows please share and thanks in advance.

A: Keychain:
It has two level encryption options

*

*lock screen passcode as the encryption key

*key generated by and stored on the device)
But when the device is jailbroken its not safe too.
oAuth:
Eventhough you store credentials in server you'll have to save the OAuth TOKEN in client side there is no place better than keychain to store it in client side.So now comes possibility of extracting the TOKEN on jailbroken device.
As far as I know in most apps they use one of these approaches.
If you need those data to be very very secure.
Suggestions:

*

*Store OAuth token in server not in client

*Store the Encrypted Credentials in Keychain and store the encryption key in server.This approach would be easy for you since you said adopting OAuth is hard for you.
Note:
There are some open source libraries available which detects if the device you run or app is cracked if so you can take action like deactivating TOKEN,deleting critical resources,locking app etc.


text:
Q: SOAP API fails with "couldn't load from…", "failed to load external entity…" When calling upon the Magento SOAP API I get the well known
SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://{domain}/index.php/api/v2_soap/index/?wsdl=1' : failed to load external entity "http://{domain}/index.php/api/v2_soap/index/?wsdl=1"

however, loading the wsdl with file_get_contents works, and even the following simple test (in a seperate file) works fine.
$server = new SoapServer('http://{domain}/index.php/api/v2_soap/index/?wsdl=1', array(
    'encoding'     => 'UTF-8',
    'soap_version' => 2));

Then again, if i take the above and use in inside the Zend Soap Server class (where the server is created), it throws the same error.
Does anybody have any ideas what's going wrong here?

A: Here is the URL I use successfully for V2 API calls:

http://{domain}/index.php/api/v2_soap?wsdl=1

Also make sure you have correct web services user set up in Magento etc. etc.

$mage_url = 'http://{domain}/index.php/api/v2_soap?wsdl=1';
$mage_user = 'USERNAME'; //Set in Magento
$mage_api_key = 'USERKEY'; //Set in Magento
$soap = new SoapClient($mage_url);
$session = $soap->login($mage_user,$mage_api_key);

That is how I do it, and it works both internally and externally. Hope this helps!


text:
Q: Declare twice beginTransaction to make it work I need to declare twice this line $connection->beginTransaction(); to make code works, otherwise if I write this line once, it throws the error There is no active transaction. Why? Is it possible to fix this?
I'm using Symfony 6.
Here is my code:
public function flushTable($em, $entityName, $io)
{
    $classMetaData = $em->getMetadataFactory()->getMetadataFor($entityName);
    $connection = $em->getConnection();
    $dbPlatform = $connection->getDatabasePlatform();
    // write this line twice otherwise it doesn't work
    $connection->beginTransaction();
    $connection->beginTransaction();

    try
    {
        $connection->query('SET FOREIGN_KEY_CHECKS=0');
        $q = $dbPlatform->getTruncateTableSql($classMetaData->getTableName());
        $connection->executeUpdate($q);
        $connection->query('SET FOREIGN_KEY_CHECKS=1');
        $connection->commit();

        $io->success(sprintf('Database flushed'));
    }
    catch (\Exception $e)
    {
        $connection->rollback();

        $io->error(sprintf($e));
    }
}


text:
Q: Bash for loop on remote server I am new to bash and I am trying to create a script that checks for malicious files. Specifically those using global PHP variables to hide content. Below is an example line of such file:
$GLOBALS['qahtm46']($zadoh31) < 12) { $GLOBALS['wlcrh95']($i34, $gxfej87);

I need to check and get the results remotely, here is how I currently connect and fetch other information:
eval=$(ssh -q -t -o GSSAPIAuthentication=yes user@$webs "/usr/bin/ssuu $domain" << EOF
grep -l -r --include=*.php -PHn "(eval\(.*\);)" .
exit
EOF
)

When I echo $eval it prints the filename of any matches. Great!
Whenever I run the below command on the server directly:
for x in $(find public_html -type f -name '*.php' | xargs grep -ol 'GLOBALS'); do grep -o 'GLOBALS' $x | wc -l | tr '\n' ' ' ; echo $x; printf "\n"; sleep 1; done
exit
EOF
)

I get the correct Output:
1 public_html/update.php
363 public_html/sites/all/themes/corporate_blue/images/proxy2.php
363 public_html/sites/all/themes/corporate_blue/images/proxy.php
2 public_html/sites/all/modules/views/views.api.php
2 public_html/sites/all/modules/imce/tpl/imce-page.tpl.php
1 public_html/sites/all/modules/ckeditor/includes/filemanager.config.php
4 public_html/modules/simpletest/drupal_web_test_case.php

However when I run this using my usual method I do not get any output, if I output to a file, the file is created but nothing is written to it:
globals=$(ssh -q -t -o GSSAPIAuthentication=yes user@$webs "/usr/bin/ssuu $domain" << EOF
for x in $(find public_html -type f -name '*.php' | xargs grep -ol 'GLOBALS'); do grep -o 'GLOBALS' $x | wc -l | tr '\n' ' ' ; echo $x; printf "\n"; sleep 1; done
exit
EOF
)

Can anybody see the problem?

A: When you run this:
ssh server << EOF
for x in $(find ...); ...
EOF

The content of the here-document gets evaluated by the local shell before passing the script to the server.
To have it evaluated on the server, double-quote the opening EOF:
ssh server << "EOF"
for x in $(find ...); ...
EOF


text:
Q: Android I get Your Xcode is outdated error on installing ADB when i want to install android-platform-tools i get error:
Ebtekars-MacBook-Pro:Android mahdi$ brew install android-platform-tools
Error: Your Xcode (8.0) is outdated.
Please update to Xcode 8.1 (or delete it).
Xcode can be updated from the App Store.

My xcode version on App Store is 8.1 and its updated to last version but i get error. how can i resolve this problem?


text:
Q: jquery: add a style attribute to existing style Add a style attribute to existing style properties
I have a div element:

I want to set border on onsubmit event:

Is there a way to do this:
Append new style attribute (border) to existing styles (with out reading existing styles)?

A: As an alternative to manipulating the style directly you could have a css class:
.submitted
{
    border: 1px #F00 solid;
}

Then using jQuery:
$('#permissions').addClass('submitted');

Then to remove:
$('#permissions').removeClass('submitted');

Then if you want to reuse the same approach elsewhere, you can just use the submitted class. Also if you want to extend the class (e.g. change the color) you can just edit the submitted class.

A: You can use the css() method of jquery:
$('#permissions').css('border','1px #000 dashed');

A: You can add style to existing style or override existing style like this.
var style =$('#permissions').attr('style'); //it will return string
//on submit update style as
style += ';border: 1px #F00 solid;';
$('#permissions').attr('style',style);

It will not affect your existing style and will add your new style to existing one even if you'll have to override any other property as well.

A: Sure:
$('#permissions').css({
  borderWidth: 1,
  borderColor: '#fff',
  borderStyle: 'solid'
});

JS Fiddle.

A: You can do this:
$('form').submit(function(){
  $('#permissions').css("border","1px #F00 solid");
});


text:
Q: jQuery Tools gallery with thumbnails Need to slide instead of fade I am currently trying to get this image gallery on jQuery tools to switch the sliding gallery instead of fading.
http://jquerytools.org/demos/scrollable/gallery.html
I was curious how I would go about doing that.
$(".items img").click(function() {
// see if same thumb is being clicked
if ($(this).hasClass("active")) { return; }

// calclulate large image's URL based on the thumbnail URL (flickr specific)
var url = $(this).attr("src").replace("_t", "");

// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap").fadeTo("medium", 0.5);

// the large image from www.flickr.com
var img = new Image();

// call this function after it's loaded
img.onload = function() {

    // make wrapper fully visible
    wrap.fadeTo("fast", 1);

    // change the image
    wrap.find("img").attr("src", url);

};

// begin loading the image from www.flickr.com
img.src = url;

// activate item
$(".items img").removeClass("active");
$(this).addClass("active");

// when page loads simulate a "click" on the first image
}).filter(":first").click();

A: You can use one of the following events,
 $(<element>).slideIn(); // display image
 $(<element>).slideOut(); //remove image

A: try var wrap = $("#image_wrap").animate("width", 0);


text:
Q: How to make a button in html that keep pressed till i press it again? I have a button that opens a popup form, but I need that when I click it again, it closes the form, there is a way to do that? I wonder if I need to destroy the button when I click it and automatically creates another equal button that closes the form.
The button
<button class="open-button" onclick="openForm()">Open Form</button>

script

A: The better way is to play around with styles. I have a simple code that might help you. Concentrate on the styles I am using here. It's about the border and the User Experience.

window.onload = function() {
  document.querySelector("button").onclick = function(e) {
    e.preventDefault();
    document.querySelector(".menu-holder").classList.toggle("active");
  };
};
* {
  font-family: 'Open Sans';
  line-height: 1;
  margin: 0;
  padding: 0;
}

button {
  border: 2px outset #ccc;
  padding: 5px;
  cursor: pointer;
}

button:hover,
.menu-holder.active button {
  border-style: inset;
}

button:active, button:focus {
  outline: none;
}

.menu {
  width: 150px;
  margin: 5px 0 0;
  padding: 10px;
  border: 2px solid #ccc;
  display: none;
}

.menu-holder.active .menu {
  display: block;
}

  <button>Menu</button>

Hi, I am Menu!

Preview
Here's a normal mode vs. selected mode:

Update: For Open / Close text, it's easier using CSS too. Check this out:

window.onload = function() {
  document.querySelector("button").onclick = function(e) {
    e.preventDefault();
    document.querySelector(".menu-holder").classList.toggle("active");
  };
};
* {
  font-family: 'Open Sans';
  line-height: 1;
  margin: 0;
  padding: 0;
}

button {
  border: 2px outset #ccc;
  padding: 5px;
  cursor: pointer;
}

button:hover,
.menu-holder.active button {
  border-style: inset;
}

button:active, button:focus {
  outline: none;
}

.menu {
  width: 150px;
  margin: 5px 0 0;
  padding: 10px;
  border: 2px solid #ccc;
  display: none;
}

.menu-holder.active .menu {
  display: block;
}

button span {
  display: none;
}
button span:first-child {
  display: inline;
}

.menu-holder.active button span {
  display: inline;
}
.menu-holder.active button span:first-child {
  display: none;
}

  <button>OpenClose Menu</button>

Hi, I am Menu!

Preview
Here we can see that the Open / Close is also controlled by CSS:

A: You can do something like :
<button id="form-button" onclick="toggleForm()">Open Form</button>

A: And this decision is from me. The toggle() method is used here.

let button_toggle = document.querySelector('.open-close');
let form = document.querySelector('#myForm');

button_toggle.onclick = function() {
  form.classList.toggle('show');
  this.innerText = this.innerText == 'Open Form' ? 'Close Form' : 'Open Form';
}
#myForm {
  display: none;
}

.show {
  display: block!important;
}
<button class="open-close">Open Form</button>
<form id="myForm">
  This is text from form
</form>


text:
Q: SQL - Time Between Each Task Update I need to calculate the time between each task update for the same activity id.  For example
  ActivityID 1 Task 1 = Started,    Audit Event Time = Date/Time
  ActivityID 1 Task 2 = In progress, Audit Event Time = Date/Time
  ActivityID 1 Task 3 = Complete, Audit Event Time = Date/Time
  ActivityID 2 Task 1 = Started,    Audit Event Time = Date/Time
  ActivityID 2 Task 2 = In progress, Audit Event Time = Date/Time
  ActivityID 2 Task 3 = Complete, Audit Event Time = Date/Time

etc.
What would be the proper sql code to subtract for activity Id 1, task 1 from 2 and 2 from 3, then do the same for activity id 2 etc?
The below query retrieves the sample data needed without the calculation.
SQL Query
 SELECT a.Subject, a.ActivityId, a.ActivityCategory, a.TaskStatusID AS TaskStatus,
 a.AuditEventTime, t.TaskStatusID, t.TaskStatusName, p.ActivityID AS ActivityNum,
 p.PortfolioID, b.PortfolioBaseID, b.CustodianBank
 FROM advapp.vActivity_Hist2 a
 JOIN APXUser.vTaskStatus t ON t.TaskStatusID = a.TaskStatusID
 LEFT JOIN AdvApp.vActivityPortfolio p ON p.ActivityID = a.ActivityID
 LEFT JOIN AdvApp.vPortfoliobaseCustom b ON b.PortfolioBaseID = p.PortfolioID
 Where ActivityCategory = 'Wire Transfers'
 AND StartDate > Convert(date,'2022-07-01')
 Order by ActivityID Asc, TaskStatus

Sample Output
[Screenshot of output]

A: you can use lag, and to incorporate it to your query:
 SELECT a.Subject, a.ActivityId, a.ActivityCategory,
        a.TaskStatusID AS TaskStatus, a.AuditEventTime,
        t.TaskStatusID, t.TaskStatusName, p.ActivityID AS ActivityNum,
        p.PortfolioID, b.PortfolioBaseID, b.CustodianBank,
        datediff(a.AuditEventTime,lag(a.AuditEventTime,1,a.AuditEventTime) over (partition by a.ActivityId order by a.AuditEventTime)) AS EventGap
 FROM advapp.vActivity_Hist2 a
 JOIN APXUser.vTaskStatus t ON t.TaskStatusID = a.TaskStatusID
 LEFT JOIN AdvApp.vActivityPortfolio p ON p.ActivityID = a.ActivityID
 LEFT JOIN AdvApp.vPortfoliobaseCustom b ON b.PortfolioBaseID = p.PortfolioID
 Where ActivityCategory = 'Wire Transfers'
 AND StartDate > Convert(date,'2022-07-01')
 Order by ActivityID Asc, TaskStatus


text:
Q: For loop to process a list of all students and their online status I'm trying to write a "for loop"( has to bee done as a for loop ) that uses the variable prefix which contains the class id, that will process all students matching the id and indicating if they are online.
for i in $prefix
do
name=$(grep $i /etc/passwd | cut -d ':' -f5)
echo -u |grep  "$i"  || test && echo "$name is Online"  || echo "$name is
Offline"
done

The output I get is
 John Doe
 Jane Smith
 Ravey Smith is currently offfline

The output I need to get is
John Doe is online
Jane Smith is offline
Ravey Smith is online


text:
Q: Numba - TypeError: 'type' object has no attribute '__getitem__ I am using Numba with Anaconda and wondering why
@jit(argtypes=[int16[:], int16[:]])
def index(ic, nc):
    return ic[0] + nc[0] * (ic[1] + nc[1] * ic[2])

does not work:
TypeError: 'type' object has no attribute '__getitem__'

But if I use @autojit instead of @jit(..) everything is fine.

A: This is slightly confusing from reading the Numba examples, but you actually need to import int16 from the numba namespace.
The error you are seeing is consistent with importing int16 from NumPy.  So if at the top of your file, your code looks like:
from numba import *
from numpy import *

Then you'll accidentally override int16 with the NumPy definition of it.  There are two fixes.  First, you could just swap the order of your imports:
from numpy import *
from numba import *

Or, more correctly, you could import the namespaces without the * and refer explicitly to what you need:
import numba as nb

@nb.jit(argtypes=[nb.int16[:], nb.int16[:]])


text:
Q: Missing required parameters for [Route: projects.edit] [URI: projects/{project}/edit] Laravel 6.3 This error has blocked me way forward. Does anyone have a solution to the Missing required parameters error?  I have a very simple CRUD setup which throws this error in the Controller 'edit' method.  This happens when the request is forwarded to the edit view.
Error:
```Facade\Ignition\Exceptions\ViewException
Missing required parameters for [Route: projects.edit] [URI:
projects/{project}/edit]. (View:
T:\estie\resources\views\frontend\layouts\homeapp.blade.php)```

Route definition is:
```Route::resource('projects','ProjectsController');```

Controller Edit method:
```public function edit(Project $project)
    {
        return view('projects.edit')  ->with('project',$project);
    }```

This is part of my index.blade.php which extends homeapp.blade.php:

        $project]) }}">EDIT

Appreciate any help, please.

A: This error is thrown when you try to get the URL of a route using the route function without providing a required parameter.
Look for the route('projects.edit') call in your homeapp.blade.php and add the project as a parameter: route('projects.edit', ['project' => $project])


text:
Q: Highcharts JS- add third variable to tooltip for two series I've already figured out how to make a chart using highcharts where there are three variables- one on the X axis, one on the Y axis, and one on the tooltip. The way to do this is to add the following to the tooltip:
tooltip: {
    formatter () {
      // this.point.x is the timestamp in my original chartData array
      const pointData = chartData.find(row => row.timestamp === this.point.x)
      return pointData.somethingElse
    }
  }

See this fiddle for the full code:
https://jsfiddle.net/m9e6thwn/
I would simply like to do the same, but with two series instead of one. I can't get it to work. I tried this:
tooltip: {
    formatter () {
      // this.point.x is the timestamp in my original chartData array
      const pointData = chartData1.find(row => row.timestamp === this.point.x)
      return pointData.somethingElse
      const pointData2 = chartData2.find(row => row.timestamp === this.point.x)
      return pointData2.somethingElse
    }
  }

Here is the fiddle of the above: https://jsfiddle.net/hdeg9x02/ As you can see, the third variable only appears on one of the two series. What am I getting wrong?

A: There are some issues with the way you are using the formatter now. For one, you cannot have two returns in the same function without any if clauses. That will mean that only the first return will be used.
Anyway, here are some improvements I suggest you do for your code.
Add the extra information for each point to highcharts, that makes it a lot easier to access this information through highcharts. E.g. in a tooltip. You can set the data like this:
chartData1.map(function(row) {
  return {
    x: row.timestamp,
    y: row.value,
    somethingElse: row.somethingElse
  }
})

If you do that, then returning the correct tooltip for each series is a simple matter of doing this:
tooltip: {
  formatter () {
    // this.point.x is the timestamp in my original chartData array
    return this.point.somethingElse
  }
}

Working JSFiddle example: https://jsfiddle.net/ewolden/dq7L64jg/6/
If you wanted more info in the tooltip you could then do:
tooltip: {
  formatter () {
    // this.point.x is the timestamp in my original chartData array
    return this.point.somethingElse + ", time: " + str(this.x) + ", value: " + str(this.y)
  }
}

Addtionally, you need to ensure that xAxis elements, i.e. your timestamps are sorted. This is a requirement for highcharts to function properly. As it is, your example is reporting

Highcharts error #15: www.highcharts.com/errors/15

in console, because chartData2 is in reverse order. It looks okay for this example, but more complicated examples can lead to the chart not looking as you expect it to.
For this example using reverse is easy enough: data: chartData2.reverse().map(function(row) {return {x: row.timestamp, y: row.value, somethingElse: row.somethingElse}})
Working JSFiddle example: https://jsfiddle.net/ewolden/dq7L64jg/7/


text:
Q: IIS7.5: Is there a way to use Require SSL and URL Rewrite Module together for https? In IIS7.5, I have a URL Rewrite rule that redirects http requests to https. If I check "Require SSL", I get a 403 Unauthorized instead of a redirect, which makes sense.
Is there a way to use them together? Would there even be a benefit? I'm assuming no since every http request would be redirected, but I'm checking here in case I'm wrong.
Is this secure?

A: The 2 options work a very different way.
If you use the Require SSL option, every single page of your website has to be accessed by HTTPS and it means that (as you have seen it), if you forget the HTTPS and try to access with HTTP, you will have a 403 Unauthorized.
If you use the URL Rewrite Module, you can setup some pages or your whole website to be redirected to HTTPS (and some part back to HTTP if needed), and if a user forgets the HTTPS and hits the HTTP, he/she will be redirected to the HTTPS url.
As of having them to work together, there is a solution, but I don't really see the point:

[...] you will need to disable "Require SSL" checkbox for the web
  site. If you do not want to do that, then you can create two web sites
  in IIS – one with http binding and another with https binding – and
  then add this rule to the web.config file of the site with http
  binding.

http://blogs.iis.net/ruslany/archive/2009/04/08/10-url-rewriting-tips-and-tricks.aspx
(Section 4. Redirect to HTTPS)


text:
Q: export_graphviz extratreesclassifier python visualization Is there a way to use export_graphviz to represent the final tree of extratreesclasiffier? If not, how can it be visually representented?

A: I think there is no way to visualize a specific tree from sklearn.ensemble.ExtraTreesClassifier.
But you can visualize it with a single tree from sklearn.tree.ExtraTreeClassifier.
from sklearn import tree
...

#Fit an Extra Tree model to the data
model = tree.ExtraTreeClassifier()
model.fit(X_train, y_train)

#Use http://webgraphviz.com to visualize the graph of this file
with open("tree_classifier.txt", "w") as f:
    f = tree.export_graphviz(model, out_file=f)

Here an example with Decision tree that also work with Extra tree:
http://dataaspirant.com/2017/04/21/visualize-decision-tree-python-graphviz/


text:
Q: $(window).scroll() firing on page load Is there a way to prevent $(window).scroll() from firing on page load?
Testing the following code in Firefox 4, it fires even when I unplug the mouse.
jQuery(document).ready(function($){
$(window).scroll(function(){
                console.log("Scroll Fired");
    });
});

A: This was the solution I went for. Any improvements gratefully received.
   var scroll = 0;
    $(window).scroll(function(){
                    if (scroll>0){
                    console.log("Scroll Fired");
                    }
                    scroll++;
    });

A: The scroll event does not fire on every load, only when refreshing a page that was scrolled, or when navigating to an anchor directly.
Many of the answers suggest ignore the first time it's called, which would ignore a valid scroll if the page doesn't get scrolled initially.

//Scroll the page and then reload just the iframe (right click, reload frame)

//Timeout of 1 was not reliable, 10 seemed to be where I tested it, but again, this is not very elegant.
//This will not fire initially
setTimeout(function(){
  $(window).scroll(function(){
     console.log('delayed scroll handler');
  });
}, 10);

//This will fire initially when reloading the page and re-establishing the scroll position
$(window).scroll(function(){
  console.log('regular scroll handler');
});
div {
  height: 2000px;
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
</div>

A: This seems to have worked for me.
$(window).bind("load", function() {
    $(window).on("scroll", function () {
        console.log('scroll');
    });
});

A: The scroll event is unrelated to the mouse, it is called whenever a new document scrolling position is set. And arguably that position is set when the document loads (you might load it with an anchor after all), also if the user presses a cursor key on his keyboard. I don't know why you need to ignore the initial scroll event but I guess that you only want to do it if pageYOffset is zero. That's easy:
var oldPageYOffset = 0;
$(window).scroll(function(){
  if (window.pageYOffset != oldPageYOffset)
  {
    oldPageYOffset = window.pageYOffset;
    console.log("Window scrolling changed");
  }
});

Note: MSIE doesn't have window.pageYOffset property so the above will need to be adjusted. Maybe jQuery offers a cross-browser alternative.

A: sure, don't load it until after the load. make it a call back for sleep for 500 millis.


text:
Q: How to search for a regular expression in c++? I'm working on C++,
I need to search for a given regular expression in given string. Please provide me the pointer to do it. I tried to use boost::regex library.
Following is the regular expression:
regular expression to search  : "get*"
And above expression i have to search in following different strings:
e.g.
1.    "com::sun::star:getMethodName"
2.    "com:sun:star::SetStatus"
3.    "com::sun::star::getMessage"

so i above case i should get true for first string false for second and again true for third one.
Thanks in advance.

A: boost::regex re("get.+");

example.
#include <iostream>
#include <string>
#include <boost/regex.hpp>
#include <vector>
#include <algorithm>

int main()
{
   std::vector<std::string> vec =
   {
      "com::sun::star:getMethodName",
      "com:sun:star::SetStatus",
      "com::sun::star::getMessage"
   };
   boost::regex re("get.+");
   std::for_each(vec.begin(), vec.end(), [&re](const std::string& s)
   {
      boost::smatch match;
      if (boost::regex_search(s, match, re))
      {
         std::cout << "Matched" << std::endl;
         std::cout << match << std::endl;
      }
   });
}

http://liveworkspace.org/code/7d47ad340c497f7107f0890b62ffa609


text:
Q: Bash: filtering and replacing by pattern Given this string of paths, separated by spaces:
path/folderA/fileA1 path/folderA/subFolderA/fileA2 path/folderB/fileB1

*

*I would like to get a string of paths, separated by spaces, only the ones starting with path/folderA/.
Output: path/folderA/fileA1 path/folderA/subFolderA/fileA2

*Then remove any match of path/folderA/ from this string.
Final output: fileA1 subFolderA/fileA2
Could this be done with a single line?

A: If you're starting with a string you run the risk that embedded spaces, newlines, or other problematic characters can throw things off. That's why it's usually better to work with globs or null-terminated values.
That said, you can use various builtins and expansions to get the results you want from your given example. Note that you must escape your forward slashes properly or store them in a quoted string to avoid interfering with the expansion syntax. For example:
path_str="path/folderA/fileA1 path/folderA/subFolderA/fileA2 path/folderB/fileB1"
match_str="path/folderA/"

read -ra paths <<< "$path_str"
for i in "${!paths[@]}"; do
    [[ ! "${paths[i]}" =~ $match_str ]] && unset paths[i]
done

echo "${paths[@]//$match_str}"

This will print:

fileA1 subFolderA/fileA2

A: With grep.
echo " $str" | grep -oP '(?<=\spath/folderA/)\S+' | xargs

-P enables the use of Perl regexp syntax and you can use (?<=pattern) which is a positive look-behind assertion. Also -o keeps only the matched part after that pattern, which is \S+, a sequence of non-white-space characters (until we find the next space, tab, newline etc.)
Also grep output is always separated by newlines, so you have to pipe to tr '\n' ' ' or xargs or similar to get one line.
Edit: to match only the beginning of the path, I added \s (one whitespace character) and feed the input as " $str". This seemed easier fix, because \b matches / also, and (^|\s) throws grep: lookbehind assertion is not fixed length. So testing with this is ok:
> echo "$str"
path/folderA/fileA1 path/folderA/subfolderA/fileA2 path/path/folderA/not
> echo " $str" | grep -owP '(?<=\spath/folderA/)\S+' | xargs
fileA1 subFolderA/fileA2

A: You can do it simply with awk matching the last set of word characters in each field and outputting them, e.g.
awk '{for (i=1; i<=NF; i++) if ($i ~ /folderA/) { match($i,/\w+$/); print substr($i,RSTART,RLENGTH)}}' <<< $path_str

Example Use/Output
path_str="path/folderA/fileA1 path/folderA/subFolderA/fileA2 path/folderB/fileB1"
awk '{for (i=1; i<=NF; i++) if ($i ~ /folderA/) { match($i,/\w+$/); print substr($i,RSTART,RLENGTH)}}' <<< $path_str
fileA1
fileA2

You can adjust the output format as desired. If you want the output all on one line, or if you want to use command substitution to capture the output in a new array, it's up to you.
Using Bash Parameter Expansions
If you want to use parameter expansions with substring removal, you can use a simple loop and the expansion $(var##*/} to remove everything up to the final '/' from each path component, e.g.
path_str="path/folderA/fileA1 path/folderA/subFolderA/fileA2 path/folderB/fileB1"
for i in $path_str; do
    [[ $i =~ folderA ]] && echo ${i##*/}
done
fileA1
fileA2

For your case the parameter expansion is likely the most efficient as it is a built-in to your shell and avoids spawning a subshell. However, if you had hundreds of thousands of components, I'd probably let awk handle it then.
The set of POSIX compliant parameter expansions with substring removal are:
${var#pattern}      Strip shortest match of pattern from front of $var
${var##pattern}     Strip longest match of pattern from front of $var
${var%pattern}      Strip shortest match of pattern from back of $var
${var%%pattern}     Strip longest match of pattern from back of $var

Bash provides many, many more parameter expansion in addition to those provided by POSIX. Including everything from substring replacement to character case conversion.
Let me know if you have further questions.


text:
Q: joining tables in mySQL to get a particular column I have two tables :
- cart , cols are (painting_id, session_id, ip, user_agent)
- paintings , cols (painting_id, price)

Now I have to select the painting id from the table cart. I need to Join the two tables and get the sum of the price of all the paintings from table 'paintings'. Note the table cart doesnt have the price column , it has to be imported from the 'paintings' table. Only the sum of price of those paintings are shown which has been added into the cart table by a particular session id or email id.
Here is the query i have tried so far
SELECT p.SUM(price) FROM paintings
p JOIN cart c ON p.painting_id = c.painting_id
WHERE c.session_id = '$session'

A: It should be SUM(p.price) instead.

A: Try this query
SELECT cart.user_agent, sum(paintings.price)
from cart inner join
paintings on
cart.painting_id=paintings.painting_id
where session_id='$session'

if you want the total cost of all the users
SELECT cart.user_agent, sum(paintings.price)
from cart inner join
paintings on
cart.painting_id=paintings.painting_id
group by cart.session_id


text:
Q: Is there a way to see a history of files that have been git stashed? This is what happened:

*

*Made a lot of changes.

*Did a git stash

*git pull to get new files.

*Did a git stash pop, which lead to conflict.

*At some point I accidentally deleted my version of one of the files I changed.

Is there a way to look at the history of the file? It was stashed at one point. Is this stored anywhere?

A: To save your changes in the stash, run the command:
git stash save "OPTIONAL message for yourself"

To get your most recent stash after running git stash, use
git stash apply

To see a list of all your stashes, use
git stash list

You will get a list that looks something like this:
stash@{0}: WIP on master: 67a4e99 Merge branch1 to branch2
stash@{1}: WIP on master: 70a7a95 Add new user role

Choose a different git stash to restore with the number that shows up for the stash you want
git stash apply stash@{2}

You can also choose git stash pop, it works same as git stash apply like..
git stash pop

or
 git stash pop stash@{2}

Git stash explained


text:
Q: Python Curses Refreshing Text With a Loop I'm connecting via Linux Mint's Xfce terminal ssh (also tried ssh -t) to a Raspberry Pi running Rasperian Stretch. On the Pi I have a Python-Curses example which I modified trying to get the current time to update every few seconds "in place" over writing  itself. But it prints the time once initially and then never prints an updated time. But if I manually press "Enter" key on my laptop the time updates, if I press "Enter" fast multiple times the "enters" stack-up and the time shows updates for as many times as I pressed enter. There's probably something maybe basic I don't understand about Curses and  terminals or Python in this case. Appreciate it. Here's code:
import curses
import traceback
import datetime
import time

try:
    # -- Initialize --
    stdscr = curses.initscr()   # initialize curses screen
    curses.noecho()             # turn off auto echoing of keypress on to screen
    curses.cbreak()             # enter break mode where pressing Enter key
                                #  after keystroke is not required for it to register
    stdscr.keypad(1)            # enable special Key values such as curses.KEY_LEFT etc

    # -- Perform an action with Screen --
    stdscr.border(0)
    stdscr.addstr(5, 5, 'Hello from Curses!', curses.A_BOLD)
    stdscr.addstr(6, 5, 'Press q to close this screen', curses.A_NORMAL)

    while True:
        # stay in this loop till the user presses 'q'
        #stdscr.addstr(7, 5, 'zztop',curses.A_NORMAL)
        ti = str((datetime.datetime.now().time()))
        stdscr.addstr(8, 5, 'Time: '+ ti, curses.A_NORMAL)
        time.sleep(3)

        ch = stdscr.getch()
        if ch == ord('q'):
            break

    # -- End of user code --

except:
    traceback.print_exc()     # print trace back log of the error

finally:
    # --- Cleanup on exit ---
    stdscr.keypad(0)
    curses.echo()
    curses.nocbreak()
    curses.endwin()

A: You need to call stdscr.refresh() before sleeping to flush output to the screen.
You may also want to add stdscr.nodelay(1) to the initialization sequence in your program (i.e, right below stdscr.keypad(1)). This will make calls to stdscr.getch() non-blocking. Alternatively, you can call stdscr.timeout(3000) instead and remove the call to sleep entirely.


text:
Q: Issue producing a valid WIF key with Python 3.6 (Pythonista - iPadOS) I am having some issues with some code. I have set about a project for creating Bitcoin wallets in an attempt to turn a hobby into a learning experience, whereby I can understand both Python and the Bitcoin protocol in more detail. I have posted here rather than in the Bitcoin site as the question is related to Python programming.
Below I have some code which I have created to turn a private key into a WIF key. I have written this out for clarity rather than the most optimal method of coding, so that I can see all the steps clearly and work on issues. This code was previously a series lines which I have now progressed into a class with functions.
I am following the example from this page: https://en.bitcoin.it/wiki/Wallet_import_format
Here is my current code:
import hashlib
import codecs

class wif():

    def private_to_wif(private_key):

        extended_key = wif.create_extended(private_key)
        address = wif.create_wif_address(extended_key)

        return address

    def create_extended(private_key):

        private_key1 = bytes.fromhex(private_key)
        private_key2 = codecs.encode(private_key1, 'hex')
        mainnet = b'80'
        #testnet = b'ef'
        #compressed = b'01'
        extended_key = mainnet + private_key2

        return extended_key

    def create_wif_address(extended_key):

        first_hash = hashlib.sha256(extended_key)
        first_digest = first_hash.digest()
        second_hash = hashlib.sha256(first_digest)
        second_digest = second_hash.digest()
        second_digest_hex = codecs.encode(second_digest, 'hex')
        checksum = second_digest_hex[:8]
        extended_key_chksm = (extended_key + checksum).decode('utf-8')
        wif_address = base58(extended_key_chksm)

        return wif_address

def base58(extended_key_chksm):

        alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
        b58_string = ''
        leading_zeros = len(extended_key_chksm) - len(extended_key_chksm.lstrip('0'))
        address_int = int(extended_key_chksm, 16)
        while address_int > 0:
            digit = address_int % 58
            digit_char = alphabet[digit]
            b58_string = digit_char + b58_string
            address_int //= 58
        ones = leading_zeros // 2
        for one in range(ones):
            b58_string = '1' + b58_string

        return b58_string

I then use a few lines of code to get this working, using the example private key from the above guide, as follows:
key = '0C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D'
address = wif.private_to_wif(key)
Print(address)

I should be getting the output: 5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbTLvyTJ
Instead I'm getting:
5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbWs6eYX
It's only the last 6 characters that differ!
Any suggestions and help would be greatly appreciated.
Thank you in advance.
Connor

A: I have managed to find the solution by adding a missing encoding step.
I am posting for all those who run into a similar issue and can see the steps that brought resolution.
def create_wif_address(extended_key):

    extended_key_dec = codecs.decode(extended_key, 'hex')
    first_hash = hashlib.sha256(extended_key_dec)
    first_digest = first_hash.digest()
    second_hash = hashlib.sha256(first_digest)
    second_digest = second_hash.digest()
    second_digest_hex = codecs.encode(second_digest, 'hex')
    checksum = second_digest_hex[:8]
    extended_key_chksm = (extended_key + checksum).decode('utf-8')
    wif_address = base58(extended_key_chksm)

    return wif_address

So above I added in a step to the function, at the beginning, to decode the passed in variable from a hexadecimal byte string to raw bytes, which is what the hashing algorithms require it seems, and this produced the result I was hoping to achieve.
Connor


text:
Q: How can there be radial acceleration without any radial force? It is a problem from Kleppner mechanics:

A bead of mass $m$ slides without friction on a rod that is made to rotate at a constant angular speed $\omega$. Neglect gravity.
(a) Show that $r = r_0 e^{\omega t}$ is a possible motion of the bead, where $r_0$ is the initial distance of the bead from the pivot.
(b) For the motion described in part (a), find the force exerted
on the bead by the rod.
(c) For the motion described above, find the power exerted by
the agency that is turning the rod and show by direct calculation
that this power equals the rate of change of kinetic energy of the
bead.

I am confused about the fact that how there can be radial acceleration without any radial force. Actually I can see it from equation but how can I realize the physical meaning of this?

A: To move in a circle, there needs to be cetripetal acceleration, and for that, there needs to be a centripetal force. As you yourself pointed out, there is no force along radial direction, which means that the bead cannot move in a circle.
Another way to see this is that the rod exerts a tangential force on the bead, so it gains some velocity in the tangential direction. However at the next instant, as the rod rotates through some angle, the earlier tangential direction is no longer the tangential direction; there is some radial component to it. Thus the bead travels in the radial direction due to the forces exerted by the sides of the rod.

A:
I am confused about the fact that how there can be radial acceleration without any radial force. Actually I can see it from equation but how can I realize the physical meaning of this?

For completeness, let's first include the math here.
For Newton's second law in polar coordinates we have
$$\mathbf F=m\mathbf a=m(\ddot r-r\dot\theta^2)\,\hat r+m(r\ddot\theta+2\dot r\dot\theta)\,\hat\theta$$
Now, one should be careful about what they mean by "radial acceleration". If by radial acceleration you mean $a_r=F_r/m$, then of course if there is no radial force then there is no radial acceleration. However, you seem to be more interested in $\ddot r$ as the "radial acceleration". And of course as you can see, if $F_r=\ddot r-r\dot\theta^2=0$, this does not mean that $\ddot r=0$ unless $r$ or $\dot\theta$ are $0$.
But what is happening physically? The issue here is that $\hat r$ and $\hat\theta$ change directions in space. This is different from the intuition we develop in introductory physics in Cartesian coordinates where the unit vectors are constant. Therefore, you cannot equate motion in some "direction" with acceleration in some "direction". This is because "radial" and "tangential" are not unique, constant directions; my radial could be your tangential. Indeed, as  @dnaik has already pointed out more generally, in uniform circular motion the acceleration is entirely radial, and yet there is no motion in the radial direction.
If you want to get back to this intuition, then move back to Cartesian coordinates. Of course it is harder to keep track of the forces, but it will work.


text:
Q: OCL 2.0 constraint to check if a Key-Value pair is present in the Hashtable How to write a OCL constraint to check if a particular Key-Value pair is always present in a HashTable using iterate feature in OCL? I am a beginner in OCL. Any hints or example would be helpful.

A: Take a look at the Unique operator for collections. It may be a simpler way to achieve what you want.


text:
Q: React: State is not updated as it should I have created a basic form:

On form submit, I'm converting the time from hours to minutes (if in minutes) but the problem is that state is not updating, as you can see Old Object and New Object.
This is the function in which I'm performing the update:
  const onFormSubmit = (event) => {
    event.preventDefault();
    const updatedObject = {
      name: newMovie.name,
      ratings: newMovie.ratings,
      duration: parseDuration(newMovie.duration),
    };
    console.log("Old object", newMovie);
    setNewMovie(updatedObject);
    console.log("New object", newMovie);

    if (updatedObject.duration != 0) {
      props.onNewMovieInput(newMovie);
    }
  };

This is the initial state:
const [newMovie, setNewMovie] = useState();
  const [durationError, setDurationError] = useState(false);
  const onDataUpdate = (event) => {
    const key = event.target.id;
    const value = event.target.value.trim();

    setNewMovie((prevState) => {
      return { ...prevState, [key]: value };
    });
  };

Where onDataUpdate is called on every onChange event.


text:
Q: Jquery datatables - Dropdown filter for server side processing from INNER JOIN I have modified serverside processing script with $acolumns and $bcolumns.
This is because i have used 'LEFT OUTER JOIN' for the SQL query and 'To and from date filter' to filter one of the columns for the table.
For this i have modified both $sWhere and $sQuery.
This is all working brilliantly but i cant populate the filters in the table with the values from the fields.
Any help/ guidance on this would be greatly appreciated.
Javascript:

var $oTable;
var asInitVals = new Array();
var aSelected = [];

$(document).ready(function() {
        var $oTable= $("#example").dataTable( {
        "oLanguage": {
            "sSearch": "Search:"
        },
        "sDom":"lfrtip", // default is lfrtip, where the f is the filter
        "bProcessing": true,
        "bServerSide": true,
        "bFilter": true,
        "bSearchable": true,
        "sAjaxSource": "scripts/server_processing.php",
        "aoColumns": [
            { "sName": "catname", "sTitle": "Division"} ,
            { "sName": "cname", "sTitle": "Course"} ,
            { "sName": "status", "sTitle": "Code"} ,
            { "sName": "mname","sTitle": "Module"} ,
            { "sName": "searchdateadded", "sTitle": "Created"},
            ],
        "fnRowCallback": function( nRow, aData, iDisplayIndex ) {
            if ( jQuery.inArray(aData.DT_RowId, aSelected) !== -1 ) {
                $(nRow).addClass('row_selected');
            }
        },
        //"sDom": '<"clear"fl>t<"clear"><"bottom"ip><"clear">',
        "iDisplayLength": 20,
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "fnServerParams": function (aoData, fnCallback) {
               aoData.push( { "name": "min", "value":  $('#min').val() } );
               aoData.push( { "name": "max", "value":  $('#max').val() } );
        }
        }).columnFilter({aoColumns:[
                { type:"select"},
                { type:"select"},
                { type:"select"},
                { type:"select"},
                { type:"select"}
                ]}
            );

// Implements the jQuery UI Datepicker widget on the date controls
$('#min, #max').daterangepicker({
    dateFormat: 'yymmdd',
     onClose: function(event) {
        $oTable.fnDraw();
    }
    //showOn: 'button',
    //buttonImage: '../images/calendar.jpg',
    //buttonImageOnly: true
}).change(function() {
    $oTable.fnDraw();
});

//Button to clear the filter
$('#clear').click(function(){
   $('#min').val('') ;
   $('#max').val('') ;
   $oTable.fnDraw('');
});

/* Add event listeners to the two range filtering inputs */
$('#min').keyup( function() { $oTable.fnDraw(); });
$('#min').change( function() { $oTable.fnDraw(); });

/* Add event listeners to the two range filtering inputs */
$('#max').keyup( function() { $oTable.fnDraw(); });
$('#max').change( function() { $oTable.fnDraw(); });

$('input[type=text]').addClass("idleField");

$('input[type=text]').focus(function() {
            $(this).removeClass("idleField").addClass("focusField");
            if (this.value == this.defaultValue){
            }
            if(this.value != this.defaultValue){
                this.select();
            }
        });
$('input[type=text]').focusout(function() {
            $(this).removeClass("focusField").addClass("idleField");
});

/* Click event handler */
$('#example tbody tr').live('click', function () {
        var id = this.id;
        var index = jQuery.inArray(id, aSelected);

        if ( index === -1 ) {
            aSelected.push( id );
        } else {
            aSelected.splice( index, 1 );
        }

        $(this).toggleClass('row_selected');
    } );
} );

My Serverside processing as follows:

<?php
    /*
     * Script:    DataTables server-side script for PHP and MySQL
     * Copyright: 2010 - Allan Jardine
     * License:   GPL v2 or BSD (3-point)
     */

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * Easy set variables
     */

    /* Array of database columns which should be read and sent back to DataTables. Use a space where
     * you want to insert a non-database field (for example a counter or static image)
     */
    $aColumns = array('catname','cname', 'short', 'mname', 'searchdateadded');
    $bColumns = array('cc.name','c.fullname', 'c.shortname', 'm.name', 'cm.added');

    /* Indexed column (used for fast and accurate table cardinality) */
    $sIndexColumn = "id";

    /* DB table to use */
    $sTable = "mdl_course_modules";

    /* Database connection information */
    $gaSql['user']       = "user";
    $gaSql['password']   = "password";
    $gaSql['db']         = "db";
    $gaSql['server']     = "localhost";

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * If you just want to use the basic configuration for DataTables with PHP server-side, there is
     * no need to edit below this line
     */

    /*
     * MySQL connection
     */
    $gaSql['link'] =  mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password']  ) or
        die( 'Could not open connection to server' );

    mysql_select_db( $gaSql['db'], $gaSql['link'] ) or
        die( 'Could not select database '. $gaSql['db'] );

    /*
     * Paging
     */
    $sLimit = "";
    if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
    {
        $sLimit = "LIMIT ".mysql_real_escape_string( $_GET['iDisplayStart'] ).", ".
            mysql_real_escape_string( $_GET['iDisplayLength'] );
    }

    /*
     * Ordering
     */
    if ( isset( $_GET['iSortCol_0'] ) )
    {
        $sOrder = "ORDER BY  ";
        for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
        {
            if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
            {
                $sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
                    ".mysql_real_escape_string( $_GET['sSortDir_'.$i] ) .", ";
            }
        }

        $sOrder = substr_replace( $sOrder, "", -2 );
        if ( $sOrder == "ORDER BY" )
        {
            $sOrder = "";
        }
    }

    /*
     * Filtering
     * NOTE this does not match the built-in DataTables filtering which does it
     * word by word on any field. It's possible to do here, but concerned about efficiency
     * on very large tables, and MySQL's regex functionality is very limited
     */
    $sWhere = "";
    if ( $_GET['sSearch'] != "" )
    {
        $sWhere = "AND (";
        for ( $i=0 ; $i<count($bColumns) ; $i++ )
        {
            $sWhere .= $bColumns[$i]." LIKE '%".mysql_real_escape_string( $_GET['sSearch'] )."%' OR ";
        }
        $sWhere = substr_replace( $sWhere, "", -3 );
        $sWhere .= ') ';
    }

    /* Individual column filtering */
    for ( $i=0 ; $i<count($bColumns) ; $i++ )
    {
        if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
        {
            if ( $sWhere == "" )
            {
                $sWhere = " AND ";
            }
            else
            {
                $sWhere .= " AND ";
            }
            $sWhere .= $bColumns[$i]." LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%'";
        }
    }

    if(isset($_GET['min']) && isset($_GET['max']) && $_GET['min'] != '' && $_GET['max'] != ''){
    $sWhere = "AND FROM_UNIXTIME(cm.added, '%Y%m%d') BETWEEN '$_GET[min]' AND '$_GET[max]'";
    }

    /*
     * SQL queries
     * Get data to display
     */
    $sQuery = "
        SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", "c.fullname AS cname, c.shortname AS short, m.name AS mname, cc.name AS catname, FROM_UNIXTIME(cm.added, '%Y - %M %D') AS dateadded,
        FROM_UNIXTIME(cm.added, '%d %M - %Y') AS searchdateadded")."
        FROM mdl_course_modules cm
        LEFT OUTER JOIN mdl_modules m  on cm.module=m.id
        LEFT OUTER JOIN mdl_course c  on cm.course=c.id
        LEFT OUTER JOIN mdl_course_categories cc  on c.category=cc.id
        WHERE c.category != 0 $sWhere
        $sOrder
        $sLimit
    ";

    $rResult = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
    /* Data set length after filtering */
    $sQuery = "
        SELECT FOUND_ROWS()
    ";
    $rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
    $aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
    $iFilteredTotal = $aResultFilterTotal[0];

    /* Total data set length */
    $sQuery = "
        SELECT COUNT(".$sIndexColumn.")
        FROM   $sTable
    ";
    $rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
    $aResultTotal = mysql_fetch_array($rResultTotal);
    $iTotal = $aResultTotal[0];

    /*
     * Output
     */
    $output = array(
        "sEcho" => intval($_GET['sEcho']),
        "iTotalRecords" => $iTotal,
        "iTotalDisplayRecords" => $iFilteredTotal,
        "aaData" => array()
    );

    while ( $aRow = mysql_fetch_array( $rResult ) )
    {
        $row = array();
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
            if ( $aColumns[$i] == "version" )
            {
                /* Special output formatting for 'version' column */
                $row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
            }
            else if ( $aColumns[$i] != ' ' )
            {
                /* General output */
                $row[] = $aRow[ $aColumns[$i] ];
            }
        }
        $output['aaData'][] = $row;
    }

    echo json_encode( $output );
?>


text:
Q: Image not displayed in the mail using powershell script I want to display a picture in the mail from a powershell code, below is the script used
$ImagePath="G:\DBScripts\BufferInfo_$(get-date -format `"yyyyMMdd_hhmmsstt`").png"
$BarChart.SaveImage($ImagePath,"png")
$recipient = "recipient@domain.com"
$smtpserver = "smtpserver.com"
$smtpport = "XX"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg = new-object Net.Mail.MailMessage
$attach = new-object Net.Mail.Attachment($ImagePath)
$attach.ContentType.MediaType = "image/png"
$msg.Attachments.Add($attach)
$msg.From = "ServerStats.com"
$msg.To.Add($recipient)
$msg.Subject = "DBStats"
$msg.Body = ""
$msg.IsBodyHTML = $true
$smtp.Send($msg)

And the image is -width 1800 -height 500.
I was able to receive the mail with attachment, however image is not displayed and it shows a box with X sign.

any advise would be really helpful. Thanks.
i got this fixed, as below
$Body = @"

            BufferPool Usage

            CacheStore Report-1

            CacheStore Report-2

"@

Send-MailMessage -To $recipient `
    -from "FROM" `
    -SmtpServer $smtpserver `
    -Subject "MSSQL Stats Report" `
    -BodyAsHtml -body $body `
    -Attachments $BufImagePath,$CSImagePath,$CS1ImagePath